不可捕捉的查克诺里斯例外
2022-08-31 04:12:31
我还没有尝试过,所以我不知道JVM是否会限制这样的东西,但也许你可以编译一些代码,这些代码会抛出,但在运行时提供一个类定义,它不会扩展Spredable。ChuckNorrisException
ChuckNorrisException
更新:
它不起作用。它会生成一个验证程序错误:
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
跑:
java -cp . TestVillain
Gotcha!
The end.
注释掉“扩展运行时异常”并重新编译 ChuckNorrisException.java
只有:
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"
经过深思熟虑,我成功地创建了一个无法修补的异常。然而,我选择给它起名,而不是查克,因为它是一个蘑菇云蛋母亲的例外。此外,它可能不完全是你的想法,但它肯定不能被抓住。观察:JulesWinnfield
public static class JulesWinnfield extends Exception
{
JulesWinnfield()
{
System.err.println("Say 'What' again! I dare you! I double dare you!");
System.exit(25-17); // And you shall know I am the LORD
}
}
public static void main(String[] args)
{
try
{
throw new JulesWinnfield();
}
catch(JulesWinnfield jw)
{
System.out.println("There's a word for that Jules - a bum");
}
}
瞧!未捕获的异常。
输出:
跑:
再说一遍“什么”!我敢!我敢加倍!
Java 结果: 8
构建成功(总时间:0 秒)
当我有更多的时间时,我会看看我是否也想不出别的东西。
另外,请查看以下内容:
public static class JulesWinnfield extends Exception
{
JulesWinnfield() throws JulesWinnfield, VincentVega
{
throw new VincentVega();
}
}
public static class VincentVega extends Exception
{
VincentVega() throws JulesWinnfield, VincentVega
{
throw new JulesWinnfield();
}
}
public static void main(String[] args) throws VincentVega
{
try
{
throw new JulesWinnfield();
}
catch(JulesWinnfield jw)
{
}
catch(VincentVega vv)
{
}
}
导致堆栈溢出 - 同样,异常仍未捕获。