What can you throw in Java?

后端 未结 3 1517
眼角桃花
眼角桃花 2020-12-05 05:59

Conventional wisdom says you can only throw objects that extend Throwable in Java, but is it possible to disable the bytecode verifier and get Java to compile a

3条回答
  •  甜味超标
    2020-12-05 06:55

    As mentioned in John's answer, you can disable verification (placing the class on the bootclasspath should also work ), load and execute a class throwing a non-Throwable class successfully.

    Surprisingly, it doesn't necessarily lead to a crash!

    As long as you don't call Throwable methods implicitly or explicitly, everything will work perfectly fine:

    .source ThrowObject.j
    .class public ThrowObject
    .super java/lang/Object
    
    .method public ()V
        aload_0
        invokenonvirtual java/lang/Object/()V
        return
    .end method
    
    .method public static main([Ljava/lang/String;)V
    
        new java/lang/Object
        dup
        invokenonvirtual java/lang/Object/()V
    
      BeforeThrow:
        athrow
    
      AfterThrow:
    
        return
    
      CatchThrow:
    
        getstatic java/lang/System/out Ljava/io/PrintStream;
        ldc "Thrown and catched Object successfully!"
        invokevirtual java/io/PrintStream.println(Ljava/lang/String;)V
        return
    
      .catch all from BeforeThrow to AfterThrow using CatchThrow
    .end method
    

    Result:

    % java -Xverify:none ThrowObject
    Thrown and catched Object successfully!
    

提交回复
热议问题