try {
someMethodThatCouldThrowAnything();
} catch (IKnowWhatToDoWithThisException e) {
handle(e);
} catch (Throwable t) {
Throwables.propagateIfInstanceOf(t, IOException.class);
Throwables.propagateIfInstanceOf(t, SQLException.class);
throw Throwables.propagate(t);
}
is not very concrete. How would a real program look like? I don't really understand the purpose of the methods Throwables.propagateIfInstanceOf(Throwable, Class)
, propagate()
, propagateIfPossible()
. When do I use them?
One scenario I can provide for anyone who'll find this useful is if you have a method wrapping any exceptions thrown, then this can be used to unwrap/cast the cause into specific exception.
Example: the get method in Guava's LoadingCache wraps all checked exceptions into ExecutionException. The documentation states that the exception can be inspected using getCause().
Here
Throwables.propagateIfInstanceOf
can be used to throw specific exceptions for the calling method to handle, if we know thatcache.get()
will throw those exceptions (maybe specific to LoadingCache, but if value is misisng, the cache tries to load a value which can throw checked exceptions).The purpose of these methods is to provide a convenient way to deal with checked exceptions.
Throwables.propagate()
is a shorthand for the common idiom of retrowing checked exception wrapped into unchecked one (to avoid declaring it in method'sthrows
clause).Throwables.propagateIfInstanceOf()
is used to retrow checked exceptions as is if their types are declared inthrows
clause of the method.In other words, the code in question
is a shorthand for the following code:
See also:
I have gone through the documentation of the Guava Throwables and I haven't found them really useful. Using throw new RuntimeException(e) is simpler to comprehend than Throwables.propagate(), in the scenario where you want to throw an unchecked exception wrapping a checked exception.