java - 将 RuntimeException 作为异常重新抛出

标签 java exception try-catch runtimeexception

Java 允许我毫无问题地编译以下代码:

public class Test {
    public static void main(String[] args){
        try {
            throw new RuntimeException();
        } catch (Exception e) {
            throw e;
        }
    }
}

尽管java.lang.Exception是一个已检查的异常。这意味着我将重新抛出未经检查的异常作为已检查的异常,并摆脱它。

很可能 Java 编译器能够发现 try block 中没有抛出已检查的异常,但我在规范中找不到备份该异常的部分。

可以依赖这种行为并从哪个 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/

相关文章:

c++ - 无法捕获的异常?

java - 创建主方法与静态方法的实例

java - 错误: Unresolved compilation problem: RetailItem cannot be resolved to a variable

java - 在具有不同流程的两个 Activity 之间使用变量

python - 在 python 中编写多个 try 和 except

ios - 闭包内的 try-catch -> 从抛出函数类型到非抛出函数类型的无效转换

Java获取包中的所有文件

java - 如何以用户友好的方式过滤错误消息,而无需在 Android 中创建自定义字符串?

exception - ule子-未针对特定异常调用捕获异常策略

java - 我应该抛出什么异常