views:

512

answers:

5

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

ie:


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.

A: 

No I do not believe so. The catch block will run to completion before the finally block.

try {
    // code that may or may not throw an exception
} catch {
// catch block must exist.
finally {
    SomeCleanupFunctionThatThrows();
// this portion is ran after catch block finishes
}

Otherwise you can add a synchronize() object that the exception code will use, that you can check in the finally block, which would help you identify if in a seperate thread you are running an exception.

zxcv
this is wrong, there is absolutely no requirement to have a catch block.
shsteimer
+1  A: 

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
    }
}
ReaperUnreal
+11  A: 

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
   }
}
Chris B.
You are just too quick...you scooped my answer
martinatime
A: 

Do you mean you want the finally block to act differently depending on whether the try block completed successfully?

If so, you could always do something like:

boolean exceptionThrown = false;
try {
    // ...
} catch(Throwable t) {
    exceptionThrown = true;
    // ...
} finally {
    try {
        SomeCleanupFunctionThatThrows();
    } catch(Throwable t) { 
        if(exceptionThrown) ...
    }
}

That's getting pretty convoluted, though... you might want to think of a way to restructure your code to make doing this unnecessary.

Rob Dickerson
+7  A: 

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();
}
Outlaw Programmer