Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this "finally" execute?

If you run the code below it actually executes the finally after every call to the goto:

    int i = 0;
Found:
    i++;
    try
    {
        throw new Exception();
    }
    catch (Exception)
    {
        goto Found;
    }
    finally
    {
        Console.Write("{0}\t", i);
    }

Why?

like image 493
Kredns Avatar asked Jul 17 '09 05:07

Kredns


People also ask

When finally will be 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.

Why is the finally statement used?

It defines a block of code to run when the try... except...else block is final. The finally block will be executed no matter if the try block raises an error or not. This can be useful to close objects and clean up resources.

Does finally always execute?

A finally block always executes, regardless of whether an exception is thrown.

Why do we use finally block to execute?

We generally use the finally block to execute clean up code like closing connections, closing files, or freeing up threads, as it executes regardless of an exception.


2 Answers

The following text comes from the C# Language Specification (8.9.3 The goto statement)


A goto statement is executed as follows:

  • If the goto statement exits one or more try blocks with associated finally blocks, control is initially transferred to the finally block of the innermost try statement. When and if control reaches the end point of a finally block, control is transferred to the finally block of the next enclosing try statement. This process is repeated until the finally blocks of all intervening try statements have been executed.
  • Control is transferred to the target of the goto statement.
like image 117
Fredrik Mörk Avatar answered Oct 09 '22 13:10

Fredrik Mörk


Why do you expect it to not execute?

If you have try/catch/finally or try/finally block, finally block executes no matter what code you may have in the try or catch block most of the time.

Instead of goto, consider 'return'.

//imagine this try/catch/finally block is inside a function with return type of bool. 
try
{
    throw new Exception();
}
catch (Exception)
{
    return false; //Let's say you put a return here, finally block still executes.
}
finally
{
    Console.WriteLine("I am in finally!");
}
like image 34
SolutionYogi Avatar answered Oct 09 '22 13:10

SolutionYogi