I have this java code with nested try:
try
{
try
{
[ ... ]
{
catch (Exception ex)
{
showLogMessage(ex);
return;
}
while (condition == true)
{
try
{
[ ... ]
{
catch (Exception ex)
{
showLogMessage(ex);
continue;
}
[ ... ]
}
}
catch (NumberFormatException e)
{
showLogMessage(e);
}
finally
{
doSomeThingVeryImportant();
}
I want to know if finally
is always executed when I get an exception. I ask this because catch blocks have return
or continue
statements.
When is doSomeThingVeryImportant()
executed? When I get an Exception
on when I get a NumberFormatException
?
I only want if after any catch block is executed, the finally block is executed also.
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.
There can only be one finally block, and it must follow the catch blocks. If the try block exits normally (no exceptions occurred), then control goes directly to the finally block. After the finally block is executed, the statements following it get control.
A finally block always executes, regardless of whether an exception is thrown. The following code example uses a try / catch block to catch an ArgumentOutOfRangeException. The Main method creates two arrays and attempts to copy one to the other.
Important Points: In C#, multiple finally blocks in the same program are not allowed.
The finally block always executes when the try block exits
(click).
Yes; or, at least, as close to "always" as possible. (So, even if you have a return
or another throw
.)
If your process is killed, or your program gets stuck in a deadlock or infinite loop, or your device is struck by a meteor, then program flow will not reach the finally
block.
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