Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When finally is executed? [duplicate]

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.

like image 711
VansFannel Avatar asked May 07 '13 06:05

VansFannel


People also ask

When finally is executed?

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.

Can we have 2 finally blocks?

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.

How many times will finally block be executed?

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.

Can we have multiple finally?

Important Points: In C#, multiple finally blocks in the same program are not allowed.


2 Answers

The finally block always executes when the try block exits (click).

like image 93
tostao Avatar answered Nov 16 '22 01:11

tostao


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.

like image 27
killscreen Avatar answered Nov 16 '22 01:11

killscreen