キャッチできないChuckNorrisException 質問する

キャッチできないChuckNorrisException 質問する

コードスニペットを構築することは可能ですか?ジャワそれは仮説をjava.lang.ChuckNorrisException捕獲不可能にするでしょうか?

思い浮かんだのは、例えば迎撃機を使うとかアスペクト指向プログラミング

ベストアンサー1

私はこれを試したことがないので、ジャバ仮想マシンChuckNorrisExceptionはこのようなことを制限しますが、 をスローするコードをコンパイルして、実行時にThrowable を拡張しない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"

おすすめ記事