Java: Checked Exceptions Without Throws-clause

Code that potentially throws checked exceptions, is often processed within a try-catch block. Two posibilities exist to forward caught exception to the caller:
- Wrap checked exception into an instance of
RuntimeException
. - 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:
- The difference between checked and unchecked exceptions only exists during compile time.
- 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
.