Class ExceptionUtils
-
Method Summary
Modifier and TypeMethodDescriptionstatic <T extends RuntimeException>
TasRuntimeException
(Throwable throwable) Reinterprets the given (usually checked) exception without adding the exception to the throws clause of the calling method.static void
-
Method Details
-
asRuntimeException
Reinterprets the given (usually checked) exception without adding the exception to the throws clause of the calling method. This method prevents throws clause inflation and reduces the clutter of "Caused by" exceptions in the stack trace.The use of this technique may be controversial, but useful.
// There is no throws clause in the method signature. public int propagateExample { try { // Throws IOException invocation(); } catch (Exception e) { // Propagates a checked exception. throw ExceptionUtils.asRuntimeException(e); } // more processing ... return value; }
This is an alternative to the more conservative approach of wrapping the checked exception in a RuntimeException:
// There is no throws clause in the method signature. public int wrapExample() { try { // throws IOException. invocation(); } catch (Error e) { throw e; } catch (RuntimeException e) { // Throws an unchecked exception. throw e; } catch (Exception e) { // Wraps a checked exception. throw new UndeclaredThrowableException(e); } // more processing ... return value; }
One downside to using this approach is that the Java compiler will not allow invoking code to specify a checked exception in a catch clause unless there is some code path within the try block that has invoked a method declared with that checked exception. If the invoking site wishes to catch the shaded checked exception, it must either invoke the shaded code through a method re-declaring the desired checked exception, or catch Exception and use the
instanceof
operator. Either of these techniques are required when interacting with non-Java JVM code such as Jython, Scala, or Groovy, since these languages do not consider any exceptions as checked.- Type Parameters:
T
- The type of the returned value.- Parameters:
throwable
- The throwable to reinterpret as aRuntimeException
.- Returns:
- throwable to reinterpreted as a
RuntimeException
.
-
illegalInstantiation
- Throws:
IllegalAccessException
-