Over a million developers have joined DZone.

Throw Checked Exceptions Like Runtime Exceptions in Java

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

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

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:

Published at DZone with permission of Lukas Eder , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}