我希望以下代码引发编译时错误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 ×1