相关疑难解决方法(0)

在没有声明的情况下,为什么在某些情况下重新抛出Throwable是合法的?

我希望以下代码引发编译时错误throw t;,因为main没有声明抛出Throwable,但它成功编译(在Java 1.7.0_45中),并产生你期望它的输出,如果编译时错误是固定.

public class Test {
    public static void main(String[] args) {
        try {
            throw new NullPointerException();

        } catch(Throwable t) {
            System.out.println("Caught "+t);
            throw t;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果Throwable更改为,它也会编译Exception.

这不会按预期编译:

public class Test {
    public static void main(String[] args) {
        try {
            throw new NullPointerException();

        } catch(Throwable t) {
            Throwable t2 = t;
            System.out.println("Caught "+t2);
            throw t2;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这编译:

public class Test {
    public static void main(String[] …
Run Code Online (Sandbox Code Playgroud)

java

23
推荐指数
1
解决办法
1849
查看次数

标签 统计

java ×1