Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Throw Checked Exceptions Like Runtime Exceptions in Java

DZone's Guide to

Throw Checked Exceptions Like Runtime Exceptions in Java

· Java Zone
Free Resource

Managing a MongoDB deployment? Take a load off and live migrate to MongoDB Atlas, the official automated service, with little to no downtime.

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

MongoDB Atlas is the easiest way to run the fastest-growing database for modern applications — no installation, setup, or configuration required. Easily live migrate an existing workload or start with 512MB of storage for free.

Topics:

Published at DZone with permission of Lukas Eder, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}