Search code examples
javaexceptionfinalthrowablechecked-exceptions

Final rethrow in Java: Exception Handling


I was going through some Exception Handling concepts in Java and came across the concept of final rethrow. I read the following article-
https://baptiste-wicht.com/posts/2010/05/better-exception-handling-in-java-7-multicatch-and-final-rethrow.html
Here, its written-

And the second improvement is a little more complicated. Imagine that you want to catch all exceptions, make several operations and then rethrow it. The code isn't hard to make, but the big problem is that you must add a throws clause to your method signature to manage the new exception launched by your code and this is not the objective. Now, you can do that without adding an exception throws clause :

     // some code
} catch (final Throwable ex) {
     // some more code
    throw ex;
}

Using the final keyword it allows you to throw an exception of the exact dynamic type that will be throwed. So if an IOException occurs, an IOException will be throwed. Of course, you have to declare the exceptions not caught. You throws clauses will exactly the same if you use the code (in //some code) without catching anything but now you can do something if that happens.

Can somebody please explain what exactly does this mean and what purpose does it solve?


Solution

  • Imagine this code:

    void m() throws IOException {
      try {
        throw new IOException();
      } catch (Exception e) {
        //do something when an exception is thrown...
        throw e;
      }
    }
    

    In Java 6, it did not compile and you had to add Exception to the method signature:

    void m() throws IOException, Exception { ... }
    

    which can be replaced by

    void m() throws Exception { ... }
    

    In other words, if you wanted to catch all exceptions, the compiler forced you to change the method signature, although in this code it is clear that only IOException can be thrown.

    The article you link to explains that, in Java 7, you can do a catch-all without changing the method signature.

    More information in the "Rethrowing Exceptions" section of this article: https://www.oracle.com/technical-resources/articles/java/java7exceptions.html.

    ps: the explanation around the final keyword is wrong, it makes no real difference in this example.