The javadoc 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);
}
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?
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's throws
clause).
Throwables.propagateIfInstanceOf()
is used to retrow checked exceptions as is if their types are declared in throws
clause of the method.
In other words, the code in question
public void doSomething()
throws IOException, SQLException {
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 a shorthand for the following code:
public void doSomething()
throws IOException, SQLException {
try {
someMethodThatCouldThrowAnything();
} catch (IKnowWhatToDoWithThisException e) {
handle(e);
} catch (SQLException ex) {
throw ex;
} catch (IOException ex) {
throw ex;
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With