Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Throwables.propagateIfInstanceOf() from Google Guava?

Tags:

java

guava

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?

like image 686
Tony Merrit Avatar asked Feb 23 '11 11:02

Tony Merrit


2 Answers

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:

  • Checked versus unchecked exceptions
  • The case against checked exceptions
like image 51
axtavt Avatar answered Oct 28 '22 20:10

axtavt


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.

like image 40
Dhiraj Avatar answered Oct 28 '22 21:10

Dhiraj