Skip to content

Instantly share code, notes, and snippets.

@tedchoward
Created August 10, 2016 14:07
Show Gist options
  • Save tedchoward/01b13366c746acf43e303dad48c746a0 to your computer and use it in GitHub Desktop.
Save tedchoward/01b13366c746acf43e303dad48c746a0 to your computer and use it in GitHub Desktop.
ExceptionUtils provides a static method that will throw a checked exception as if it were a runtime exception. You can use this to catch and re-throw a checked exception without wrapping it in a RuntimeException and muddying up the stack trace.
public class ExceptionUtils {
public static void throwException(Exception ex) {
if (ex instanceof RuntimeException) throw (RuntimeException)ex;
try {
synchronized (CheckedExceptionThrower.class) {
CheckedExceptionThrower.exception = ex;
CheckedExceptionThrower.class.newInstance();
}
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
private static class CheckedExceptionThrower {
private static Exception exception;
CheckedExceptionThrower() throws Exception {
Exception ex = exception;
exception = null;
throw ex;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment