1. Overview

In this article, we're going to take a quick look at Google Guava's Throwables class.

This class contains a set of static utility methods for dealing with exception handling and:

  • propagation
  • processing the cause chain

2. Maven Dependency


3. Propagation

Let's assume we interact with some code that throws a generic Throwable.

In most cases, we want to convert this to a RuntimeException if it's a direct subclass of Throwable.

However, if it's an instance of Error, RuntimeException or Exception we can invoke the propagateIfPossible to propagate it as-is:

try {
} catch (Throwable t) {
    Throwables.propagateIfPossible(t, Exception.class);
    throw new RuntimeException(t);

4. Causal Chain

Guava also provides utility methods for inspecting the thrown exception and its chain.

Throwable getRootCause(Throwable)

The getRootCause method allows us to get the innermost exception, which is useful when we want to find the initial cause.

List<Throwable> getCausalChain(Throwable)

This getCausalChain method will return a list of all the throwables in the hierarchy. This is handy if we want to check if it contains a certain type of exception.

String getStackTraceAsString(Throwable)

The getStackTraceAsString method will return the recursive stack trace of the exception.

5. Conclusion

In this tutorial, we illustrated some examples where we can use Guava's Throwables class to simplify dealing with exceptions.

As always, the complete source code is available over on GitHub.

Generic bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

Comments are closed on this article!