问题描述
是否有可能在 Java 中构造一段代码来生成假设的 java.lang.ChuckNorrisException
无法捕获?
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.
推荐答案
这个我没试过,所以不知道 JVM 会限制这样的事情,但也许你可以编译抛出 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.
注释掉extends 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!