A utility class that rethrows a cast as out of control?

I catch all the variables in the unit test wrapper method to reset some data in the external system. I want to repeat the original exception when this is done, and I use this piece of code for this:

if (t instanceof RuntimeException) { throw (RuntimeException) t; } else if (t instanceof Error) { throw (Error) t; } else { throw new RuntimeException(t); } 

However, does an existing service call exist?

(I catch latches because AssertionErrors are errors.)

Edit: To be honest, I really don't want to wrap an exception, so any trick that would allow me to throw any throws (including checked exceptions) without throwing throws is acceptable.

+5
source share
3 answers

Yes, there is a way to write a method that avoids the transfer of checked exceptions. It is ideal for this use case, although you should definitely be very careful with it, as it can easily confuse the uninitiated. Here it is:

 @SuppressWarnings("unchecked") public static <T extends Throwable> void sneakyThrow(Throwable t) throws T { throw (T) t; } 

and you would use it as

 catch (Throwable t) { sneakyThrow(t); } 

As Joachim Sauer commented, in some cases this helps convince the compiler that the line calling sneakyThrow will end the method. We can simply change the declared return type:

 @SuppressWarnings("unchecked") public static <T extends Throwable> T sneakyThrow(Throwable t) throws T { throw (T) t; } 

and use it like this:

 catch (Throwable t) { throw sneakyThrow(t); } 

For educational purposes, it's nice to see what happens at the bytecode level. Relevant snippet from javap -verbose UncheckedThrower :

 public static <T extends java.lang.Throwable> java.lang.RuntimeException sneakyThrow(java.lang.Throwable) throws T; descriptor: (Ljava/lang/Throwable;)Ljava/lang/RuntimeException; flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: aload_0 1: athrow Exceptions: throws java.lang.Throwable Signature: #13 // <T:Ljava/lang/Throwable;>(Ljava/lang/Throwable;)Ljava/lang/RuntimeException;^TT; 

Please note that there are no checkcast instructions. The method even legitimately announces to cast T , which can be any Throwable .

+9
source

The large Guava library has a Throwables.propagate(Throwable) method that does exactly what your code does: JavaDoc

From the doc:

Throws throwable as-is if it is an instance of RuntimeException or Error, or, as a last resort, wraps it in a RuntimeException, then throws it.

+7
source

Maybe setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler) may help you. There you can define a global exception handler for all exceptions.

0
source

All Articles