Skip to content

ThrowablesExplained

Chris Povirk edited this page Jan 20, 2017 · 24 revisions

TODO: rewrite with more examples

Guava's Throwables utility can frequently simplify dealing with exceptions.

Propagation

Sometimes, when you catch an exception, you want to throw it back up to the next try/catch block. This is frequently the case for RuntimeException or Error instances, which do not require try/catch blocks, but can be caught by try/catch blocks when you don't mean them to.

Guava provides several utilities to simplify propagating exceptions. For example:

   try {
     someMethodThatCouldThrowAnything();
   } catch (IKnowWhatToDoWithThisException e) {
     handle(e);
   } catch (Throwable t) {
     Throwables.propagateIfInstanceOf(t, IOException.class);
     Throwables.propagateIfInstanceOf(t, SQLException.class);
     throw Throwables.propagate(t);
   }

Each of these methods throw the exception themselves, but throwing the result -- e.g. throw Throwables.propagate(t) -- can be useful to prove to the compiler that an exception will be thrown.

Here are quick summaries of the propagation methods provided by Guava:

Signature Explanation
RuntimeException propagate(Throwable) Propagates the throwable as-is if it is a RuntimeException or an Error, or wraps it in a RuntimeException and throws it otherwise. Guaranteed to throw. The return type is a RuntimeException so you can write throw Throwables.propagate(t) as above, and Java will realize that that line is guaranteed to throw an exception.
void propagateIfInstanceOf(Throwable, Class) throws X Propagates the throwable as-is, if and only if it is an instance of X.
void propagateIfPossible(Throwable) Throws throwable as-is only if it is a RuntimeException or an Error.
void propagateIfPossible(Throwable, Class) throws X Throws throwable as-is only if it is a RuntimeException, an Error, or an X.

Uses for Throwables.propagate

See Why we deprecated Throwables.propagate.

Causal Chain

Guava makes it somewhat simpler to study the causal chain of an exception, providing three useful methods whose signatures are self-explanatory:

Throwable getRootCause(Throwable)
List<Throwable> getCausalChain(Throwable)
String getStackTraceAsString(Throwable)
Clone this wiki locally