Created
August 10, 2016 14:07
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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