Throw checked exceptions like runtime exceptions in Java

How 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

5 thoughts on “Throw checked exceptions like runtime exceptions in Java

Leave a Reply