Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 761
Greg Rogers Avatar asked Sep 15 '08 20:09

Greg Rogers


3 Answers

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
   }
}
like image 129
Chris B. Avatar answered Oct 23 '22 07:10

Chris B.


If you find yourself doing this, then you might have a problem with your design. The idea of a "finally" block is that you want something done regardless of how the method exits. Seems to me like you don't need a finally block at all, and should just use the try-catch blocks:

try {
   doSomethingDangerous(); // can throw exception
   onSuccess();
} catch (Exception ex) {
   onFailure();
}
like image 42
Outlaw Programmer Avatar answered Oct 23 '22 06:10

Outlaw Programmer


If a function throws and you want to catch the exception, you'll have to wrap the function in a try block, it's the safest way. So in your example:

try {
    // ...
} finally {
    try {
        SomeCleanupFunctionThatThrows();
    } catch(Throwable t) { //or catch whatever you want here
        // exception handling code, or just ignore it
    }
}
like image 1
ReaperUnreal Avatar answered Oct 23 '22 06:10

ReaperUnreal