小编典典

无法捕获的 ChuckNorrisException

all

是否有可能在Java中构造一段代码,使假设的无法java.lang.ChuckNorrisException捕获?

想到的想法是使用例如拦截器或面向方面的编程


阅读 130

收藏
2022-03-06

共1个答案

小编典典

我没有尝试过,所以我不知道JVM是否会限制这样的东西,但也许你可以编译
throws 的代码,但在运行时提供一个 不扩展
Throwable
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.

注释掉“extends RuntimeException”并 重新编译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"
2022-03-06