gpt4 book ai didi

java - 重新抛出异常而不需要抛出异常?

转载 作者:搜寻专家 更新时间:2023-11-01 03:33:29 24 4
gpt4 key购买 nike

<分区>

考虑以下代码:

static void main(String[] args) {
try {
} catch (Exception e) {
throw e;
}
}

This code compiles无需将 throws Exception 添加到方法签名。 (它的行为也与 Throwable 代替 Exception 类似)。

我理解为什么它可以安全地运行,因为 Exception 实际上不能在 try block 中抛出,所以检查不能抛出异常;我很想知道这种行为是在哪里指定的。

不仅仅是 throw e 永远不会到达:下面的代码也可以编译:

static void stillCompilesWithThrownUncheckedException() {
try {
throw new NullPointerException();
} catch (Exception e) {
throw e;
}
}

但是如果你抛出一个检查过的异常,它不会像我预期的那样编译:

static void doesNotCompileWithThrownCheckedException() {
try {
throw new Exception();
} catch (Exception e) {
throw e; // error: unreported exception Exception; must be caught or declared to be thrown
}
}

JLS Sec 11.2.2 ,它说:

A throw statement (§14.18) whose thrown expression has static type E and is not a final or effectively final exception parameter can throw E or any exception class that the thrown expression can throw.

我对这条语句的理解是throw e可以抛出Exception,因为e的静态类型是Exception。然后,在 JLS Sec 11.2.3 :

It is a compile-time error if a method or constructor body can throw some exception class E when E is a checked exception class and E is not a subclass of some class declared in the throws clause of the method or constructor.

但前两种情况都不是编译时错误。语言规范中在哪里描述了这种行为?


编辑:将其标记为欺骗后,我打算问后续问题:为什么 throw e; 在第一个示例中不被认为是不可访问的

JLS Sec 14.21 中更容易找到答案:

  • A catch block C is reachable iff both of the following are true:

    • Either the type of C's parameter is an unchecked exception type or Exception or a superclass of Exception, or some expression or throw statement in the try block is reachable and can throw a checked exception whose type is assignable to the type of C's parameter. (An expression is reachable iff the innermost statement containing it is reachable.)

      See §15.6 for normal and abrupt completion of expressions.

    • There is no earlier catch block A in the try statement such that the type of C's parameter is the same as or a subclass of the type of A's parameter.

这两个都是真的(它是Exception类型的,并且没有更早的catch block ),所以它是“可达的”。我想调用一个空的 try block 作为一种特殊情况的努力对于这样一个边缘有用的结构来说太大了。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com