I have a simple question an simple part of code, some basic try-finally
block:
try {
// Some code which can throw an Exception
} finally {
// Some code which also can throw an Exception
}
My main question would be: Is there any way we can discover is Exception thrown in finally
block without using catch
and some local variables to pass information between blocks?
I have few situations where this can be useful, and I don't want to add some ugly unnecessary catch
blocks to just set some variable and throw Exception
again. First example is that in case when I'm in some Spring or container managed transactional method, and in try
block Exception
occurred. I need to create new transaction in finally
to work with database in that case. Second example is that I don't want to my original Exception
be masked by Exception
thrown in finally
block, but if there was no Exception
I will throw it from finally
(if there was any).
I know it all can be done with catch
but is there any other way, some metadata in Java or anything else? Also it can be helpful if we can assume that this will be executed in one Thread
, so maybe there is some way to discover Exception bounded to current Thread
?
It's something that has long frustrated me.
I normally declare a variable exceptionThrown=true at the top and set it to false just before returning. Then you can test that in the finally handler. I think that's better than catching and re-throwing because the latter approach will mess up the stack trace.
I'm surprised neither Java nor C# has a better way of handling this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With