How to wrap checked exceptions but keep the original runtime exceptions in Java

AlikElzin-kilaka picture AlikElzin-kilaka · Sep 27, 2016 · Viewed 9k times · Source

I have some code that might throw both checked and runtime exceptions.

I'd like to catch the checked exception and wrap it with a runtime exception. But if a RuntimeException is thrown, I don't have to wrap it as it's already a runtime exception.

The solution I have has a bit overhead and isn't "neat":

try {
  // some code that can throw both checked and runtime exception
} catch (RuntimeException e) {
  throw e;
} catch (Exception e) {
  throw new RuntimeException(e);
}

Any idea for a more elegant way?

Answer

Peter Lawrey picture Peter Lawrey · Sep 27, 2016

I use a "blind" rethrow to pass up checked exceptions. I have used this for passing through the Streams API where I can't use lambdas which throw checked exceptions. e.g We have ThrowingXxxxx functional interfaces so the checked exception can be passed through.

This allows me to catch the checked exception in a caller naturally without needing to know a callee had to pass it through an interface which didn't allow checked exceptions.

try {
  // some code that can throw both checked and runtime exception

} catch (Exception e) {
  throw rethrow(e);
}

In a calling method I can declare the checked exception again.

public void loadFile(String file) throws IOException {
   // call method with rethrow
}

/**
 * Cast a CheckedException as an unchecked one.
 *
 * @param throwable to cast
 * @param <T>       the type of the Throwable
 * @return this method will never return a Throwable instance, it will just throw it.
 * @throws T the throwable as an unchecked throwable
 */
@SuppressWarnings("unchecked")
public static <T extends Throwable> RuntimeException rethrow(Throwable throwable) throws T {
    throw (T) throwable; // rely on vacuous cast
}

There is a lot of different options for handling exceptions. We use a few of them.

https://vanilla-java.github.io/2016/06/21/Reviewing-Exception-Handling.html