我没有尝试过,所以我不知道是否可以JVM http://en.wikipedia.org/wiki/Java_virtual_machine会限制这样的事情,但也许你可以编译抛出异常的代码ChuckNorrisException
,但在运行时提供一个类定义ChuckNorrisException
which 不扩展 Throwable.
UPDATE:
这不起作用。它会生成一个验证器错误:
Exception in thread "main" java.lang.VerifyError: (class: TestThrow, method: ma\
in signature: ([Ljava/lang/String;)V) Can only throw Throwable objects
Could not find the main class: TestThrow. Program will exit.
更新2:
实际上,如果禁用字节码验证器,您就可以让它工作! (-Xverify:none
)
更新3:
对于那些在家中关注的人,以下是完整的脚本:
创建以下类:
public class ChuckNorrisException
extends RuntimeException // <- Comment out this line on second compilation
{
public ChuckNorrisException() { }
}
public class TestVillain {
public static void main(String[] args) {
try {
throw new ChuckNorrisException();
}
catch(Throwable t) {
System.out.println("Gotcha!");
}
finally {
System.out.println("The end.");
}
}
}
编译类:
javac -cp . TestVillain.java ChuckNorrisException.java
Run:
java -cp . TestVillain
Gotcha!
The end.
注释掉“extends RuntimeException”并重新编译ChuckNorrisException.java
only :
javac -cp . ChuckNorrisException.java
Run:
java -cp . TestVillain
Exception in thread "main" java.lang.VerifyError: (class: TestVillain, method: main signature: ([Ljava/lang/String;)V) Can only throw Throwable objects
Could not find the main class: TestVillain. Program will exit.
不验证运行:
java -Xverify:none -cp . TestVillain
The end.
Exception in thread "main"