I am catching all throwables in a unit test wrapper method in order to reset some data in an external system. I want to re-throw the original exception when this is done and I am using this piece of code to do it:
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else if (t instanceof Error) {
throw (Error) t;
} else {
throw new RuntimeException(t);
}
However, is there any existing utility call that does this already?
(I am catching throwables because AssertionErrors are Errors.)
Edit: To be honest, I don't really want to wrap the exception, so any trick that would allow me to throw any throwable (including checked exceptions) without declaring throws is acceptable.
Yes, there is a way to write a method that will avoid wrapping your checked exceptions. For this use case it is a perfect match, although you should definitely be very careful with it, since it can easily confuse the uninitiated. Here it is:
and you'd use it as
As commented by Joachim Sauer, in certain cases it helps convince the compiler that the line calling
sneakyThrow
causes the method to terminate. We can just change the declared return type:and use it like this:
For educational purposes it is nice to see what's going on at the bytecode level. The relevant snippet from
javap -verbose UncheckedThrower
:Note there is no
checkcast
instruction. The method even legitimately declares to throw anyThrowable
, which is the erasure ofT
.Perhaps
setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler)
can help you. There you can define a global exception handler for all exceptions that occur.The great Guava library has a Method
Throwables.propagate(Throwable)
that does exactly what your code is doing: JavaDocFrom the doc: