-
Notifications
You must be signed in to change notification settings - Fork 10.9k
ThrowablesExplained
cpovirk edited this page Sep 25, 2023
·
24 revisions
Guava's Throwables
utility can frequently simplify dealing with exceptions.
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.
Guava makes it somewhat simpler to study the causal chain of an exception, providing three useful methods whose signatures are self-explanatory:
- Introduction
- Basic Utilities
- Collections
- Graphs
- Caches
- Functional Idioms
- Concurrency
- Strings
- Networking
- Primitives
- Ranges
- I/O
- Hashing
- EventBus
- Math
- Reflection
- Releases
- Tips
- Glossary
- Mailing List
- Stack Overflow
- Android Overview
- Footprint of JDK/Guava data structures