Piere
Piere

Reputation: 17

Why is this finally not executing?

.net 4 console app sample

When I run this in the vs 2010 it seems to keep throwing (from the catch) and never gets to the finally. It breaks on the throw and shows the exception, I hit f5 and it rethrows almost like its looping on the throw. Using similiar code in another exe I was able to throw the exception to the console and execute the finally to clean up. That is not the case not and I'm wondering why.

static void Main(string[] args)
    {
        try
        {
            throw new Exception("Exception");
        }
        catch(Exception)
        {
            Console.WriteLine("Catch");
            throw;
        }
        finally
        {
            Console.WriteLine("Finally");
        }
    }

Upvotes: 0

Views: 212

Answers (4)

Grant Thomas
Grant Thomas

Reputation: 45083

You can guarantee that it is indeed executing, as @David Heffernan demonstrated with his output; however, you might consider what is said in the C# specification (8.10) in order be confident that is should be:

The statements of a finally block are always executed when control leaves a try statement. This is true whether the control transfer occurs as a result of normal execution, as a result of executing a break, continue, goto, or return statement, or as a result of propagating an exception out of the try statement.

Upvotes: 0

Alex
Alex

Reputation: 5439

If I start the program with debugging, the code stops with the message "unhandled exception", which is before finally would be executed. Running without debugging will work as intended (CTRL-F5).

Using the debugger you can verify the finally being executed by moving your testcode inside another try-catch block, e.g.:

static void Main(string[] args)
{      
    try
    {
        Method();
    }
    catch (Exception)
    {
        Console.WriteLine("caught in main");
    }
    Console.ReadKey();
}
public static void Method()
{
    try
    {
        throw new Exception("Exception");
    }
    catch (Exception)
    {
        Console.WriteLine("Catch");
        throw;
    }
    finally
    {
        Console.WriteLine("Finally");
    }
}

Upvotes: 2

Davide Piras
Davide Piras

Reputation: 44605

I would bet the finally actually is executed, but being in the Main method of the console application, in the finally the console object is not available anymore.

Upvotes: 2

David Heffernan
David Heffernan

Reputation: 612964

On the contrary, it does execute the finally block. This is the output:

Catch

Unhandled Exception: System.Exception: Exception at ConsoleApplication1.Program.Main(String[] args) in C:\Desktop\ConsoleApplication1\Program.cs:line 24
Finally

Upvotes: 10

Related Questions