UPDATE May 2021 - When I originally asked this question, the core thing that made this question relevant (for me) was that when rethrowing an exception from a catch via a simple throw
(by itself), the original exception stack was lost. So that made using a catch to detect if an exception was thrown off-limits.
This incorrect loss-of-stack behavior was fixed sometime between when the question was asked (2017) and now. So a simple catch and rethrow (call throw
with no other arguments) is now the most straightforward way to detect an exception was thrown from the finally
block. Thanks to @JohnLBevan for his answer letting me know that rethrowing from the catch was no longer problematic.
ORIGINAL QUESTION:
I've got some code structured like this
try{
...
}
finally{
...
<code that may throw>
}
Of course one should generally avoid code that throws in a finally. But it can happen. And when it does, one unfortunate side effect is that the original exception is lost. So the first thing I'd like to do in the finally is log information about the exception thrown in the try, if one was thrown.
But how can I determine if an exception did occur in the try block, once I'm in the finally? Is there a slick way? I don't want to catch the exception in a catch. I can set a boolean at the end of the try which would indicate an exception was not thrown, but I'm not a big fan of having to do that every time. That would look like this:
$exceptionThrown = $true
try{
...
$exceptionThrown = $false
}
finally{
<if $exceptionThrown log info about it>
...
<code that may throw>
}
Can I do better?