Skip to content

ThrowablesExplained

cpovirk edited this page Sep 25, 2023 · 24 revisions

Throwables

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:

for (Foo foo : foos) {
  try {
    foo.bar();
  } catch (BarException | RuntimeException | Error t) {
    failure = t;
  }
}
if (failure != null) {
  throwIfInstanceOf(failure, BarException.class);
  throwIfUnchecked(failure);
  throw new AssertionError(failure);
}

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

Signature Explanation
void throwIfInstanceOf(Throwable, Class<X extends Exception>) throws X Propagates the throwable as-is, if and only if it is an instance of X.
void throwIfUnchecked(Throwable) Throws throwable as-is only if it is a RuntimeException or an Error.

NOTE: We deprecated Throwables.propagate(Throwable) in v20.0. Read about why.

Causal Chain

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

Clone this wiki locally