gpt4 book ai didi

java - 重新抛出 RuntimeException 作为异常

转载 作者:行者123 更新时间:2023-12-04 07:18:44 31 4
gpt4 key购买 nike

Java 允许我编译以下代码而不会出现任何问题:

public class Test {
public static void main(String[] args){
try {
throw new RuntimeException();
} catch (Exception e) {
throw e;
}
}
}
即使 java.lang.Exception是一个检查异常。这意味着我将未经检查的异常重新抛出为已检查并逃脱。
最有可能的 Java 编译器能够确定在 try 块中没有抛出已检查的异常,但我在规范中找不到备份它的部分。
可以依靠这种行为并从哪个 JDK 版本开始吗?
更新:
此类不能使用 Java 1.6.0_38 编译,并显示以下消息:
Test.java:6: unreported exception java.lang.Exception; must be caught or declared to be thrown
throw e;
^
1 error

最佳答案

看起来这是Java 7中增强的效果之一:Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking .参见 部分“使用更具包容性的类型检查重新抛出异常。”

The Java SE 7 compiler can determine that the exception thrown by the statement throw e must have come from the try block, and the only exceptions thrown by the try block can be FirstException and SecondException. Even though the exception parameter of the catch clause, e, is type Exception, the compiler can determine that it is an instance of either FirstException or SecondException.


请注意,即使在 Java 7 及更高版本中,以下内容也不会编译:
public class Test {
public static void main(String[] args){
try {
throw new RuntimeException();
} catch (Exception e) {
Exception e1 = e;
throw e1;
}
}
}
因为:

This analysis is disabled if the catch parameter is assigned to another value in the catch block.

关于java - 重新抛出 RuntimeException 作为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68635149/

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