Throw Checked Exceptions Like Runtime Exceptions in Java
Join the DZone community and get the full member experience.
Join For FreeHow to throw a checked exception without catch block or throws clause in Java? Simple!
public class Test { // No throws clause here public static void main(String[] args) { doThrow(new SQLException()); } static void doThrow(Exception e) { Test.<RuntimeException> doThrow0(e); } @SuppressWarnings("unchecked") static <E extends Exception> void doThrow0(Exception e) throws E { throw (E) e; } }
Due to generic type erasure, the compiler will compile something here that really shouldn’t compile. Crazy? Yes. Scary? Definitely!
The generated bytecode for doThrow() and doThrow0() can be seen here:
// Method descriptor #22 (Ljava/lang/Exception;)V // Stack: 1, Locals: 1 static void doThrow(java.lang.Exception e); 0 aload_0 [e] 1 invokestatic Test.doThrow0(java.lang.Exception) : void [25] 4 return Line numbers: [pc: 0, line: 11] [pc: 4, line: 12] Local variable table: [pc: 0, pc: 5] local: e index: 0 type: java.lang.Exception // Method descriptor #22 (Ljava/lang/Exception;)V // Signature: <E:Ljava/lang/Exception;>(Ljava/lang/Exception;)V^TE; // Stack: 1, Locals: 1 static void doThrow0(java.lang.Exception e) throws java.lang.Exception; 0 aload_0 [e] 1 athrow Line numbers: [pc: 0, line: 16] Local variable table: [pc: 0, pc: 2] local: e index: 0 type: java.lang.Exception
As can be seen, the JVM doesn't seem to have a problem with the checked exception thrown from doThrow0(). In other words, checked and unchecked exceptions are mere syntactic sugar
Published at DZone with permission of Lukas Eder. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments