Java: Checked Exceptions Without Throws-clause

Footballplayers throw/catch ball
Footballplayers throw/catch ball | trimmed | © Wikimedia Commons | CC BY-SA 2.0 Deed

Code that potentially throws checked exceptions, is often processed within a try-catch block. Two posibilities exist to forward caught exception to the caller:

  1. Wrap checked exception into an instance of RuntimeException.
  2. Declare a throws-clause

Both may be undesired. This article describes a technice to throw checked exceptions without the need of either. The technique is called throw sneaky. It is implemented as a static method:

@SuppressWarnings("unchecked")
public static <E extends Exception, R> R throwSneaky(Exception e)
  throws E {
    
  throw (E) e;
}

The code makes use of two things:

  1. The difference between checked and unchecked exceptions only exists during compile time.
  2. The potentially thrown checked Exception is hidden from the compiler with the help of Generics.

The following code sample will illustrate usage:

public static void main(String[] args) {
  try {
    new FileInputStream("nonexistent");
  } catch (FileNotFoundException e) {
    // Checked exception can be thrown
    // without throws clause.
    throwSneaky(e);
  }
}

The technique described is inspired by a thread on stackoverflow.com. Although it does not spare you the try-catch-Block. This is addressed by Project Lombok with the Annotation @SneakyThrows.