Search code examples
javaexceptionfault-tolerance

Fail fast finally clause in Java


Is there a way to detect, from within the finally clause, that an exception is in the process of being thrown?

See the example below:


try {
    // code that may or may not throw an exception
} finally {
    SomeCleanupFunctionThatThrows();
    // if currently executing an exception, exit the program,
    // otherwise just let the exception thrown by the function
    // above propagate
}

or is ignoring one of the exceptions the only thing you can do?

In C++ it doesn't even let you ignore one of the exceptions and just calls terminate(). Most other languages use the same rules as java.


Solution

  • Set a flag variable, then check for it in the finally clause, like so:

    boolean exceptionThrown = true;
    try {
       mightThrowAnException();
       exceptionThrown = false;
    } finally {
       if (exceptionThrown) {
          // Whatever you want to do
       }
    }