问题描述
是否可以在中构建一个代码片段,这样就可以产生一个假设 java.lang.ChuckNorrisException
uncatchable?
Is it possible to construct a snippet of code in Java that would make a hypothetical java.lang.ChuckNorrisException
uncatchable?
想到想到的是使用示例拦截器或。
Thoughts that came to mind are using for example interceptors or aspect-oriented programming.
推荐答案
我没有尝试过,所以我不知道是否会限制这样的事情,但是也许你可以编译引发 ChuckNorrisException
的代码,但是在运行时提供 ChuckNorrisException
的类定义不扩展Throwable 。
I haven't tried this, so I don't know if the JVM would restrict something like this, but maybe you could compile code which throws ChuckNorrisException
, but at runtime provide a class definition of ChuckNorrisException
which does not extend Throwable.
更新:
它不起作用。它会生成验证器错误:
It doesn't work. It generates a verifier error:
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
)
Actually, you can get this to work if you disable the byte code verifier! (-Xverify:none
)
更新3:
对于那些在家中的人,以下是完整的脚本:
For those following from home, here is the full script:
创建以下课程:
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
运行:
java -cp . TestVillain
Gotcha!
The end.
注释扩展RuntimeException和重新编译 ChuckNorrisException.java
:
Comment out "extends RuntimeException" and recompile ChuckNorrisException.java
only :
javac -cp . ChuckNorrisException.java
运行:
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"
这篇关于无可争议的ChuckNorrisException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!