开发者

Why is this finally not executing?

开发者 https://www.devze.com 2023-03-25 08:40 出处:网络
.net 4 console app sample When I run this in the vs 2010 it seems to keep throwing (from the catch) and neve开发者_C百科r gets to the finally. It breaks on the throw and shows the exception, I hit f5

.net 4 console app sample

When I run this in the vs 2010 it seems to keep throwing (from the catch) and neve开发者_C百科r 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");
        }
    }


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


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.


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");
    }
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号