Search code examples
javaexceptionguava

Is it necessary to use throw keyword with Throwables.propagate(e)?


In this code, do I need the throw keyword in order to propagate the exception?

try {
  //try something
} catch (Exception e) {
  throw Throwables.propagate(e);
}

The Throwables documentation says that this method always throws an exception - is adding the throw superfluous? Could I have written the following instead?

try {
  //try something
} catch (Exception e) {
  Throwables.propagate(e);
}

Solution

  • The javadoc also states

    The RuntimeException return type is only for client code to make Java type system happy in case a return value is required by the enclosing method.

    and then provides this example

    T doSomething() {
      try {
        return someMethodThatCouldThrowAnything();
      } catch (IKnowWhatToDoWithThisException e) {
        return handle(e);
      } catch (Throwable t) {
        throw Throwables.propagate(t);
      }
    } 
    

    In other words, the return type (RuntimeException) is necessary so you can use the method in return or throws statements.

    In the above example, if you omitted the throw in the last catch block, then the Java compiler would report an error because it cannot guarantee that a value will be returned from that catch block. A return or throws instead indicate that the method completes at that point, abruptly.