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: