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
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!