Search code examples
javaexceptiontry-catchfinally

Java lost exception


Suppose we have following method (a very simplified version):

    void doSomething() {
      try {
        throw new Exception("A");
      } finally {
        throw new Exception("B");
      }
    }

Exception with message "B" is caught in the caller method. Basically, is there any way of knowing which exception was thrown in try block if finally block also throws some exception? Suppose method doSomething() cannot be modified.


Solution

  • Section 14.20.2 of the JLS states:

    If execution of the try block completes abruptly because of a throw of a value V, ...

    ...

    If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and the throw of value V is discarded and forgotten).

    Java must discard the original exception V ("complete abruptly") and the whole try-finally block "completes abruptly" with S (the finally Exception, "B").

    There is no way to retrieve the original try block exception "A", which corresponds to V in the JLS.