Search code examples
c#exceptiontry-finally

finally not called after try


For some reason within my console application I cannot get my finally block to run. I was writing this code to test how the finally block works so it is very simple:

static void Main()
{
    int i = 0;
    try
    {
        int j = 1 / i; // Generate a divide by 0 exception.
    }
    finally
    {

        Console.Out.WriteLine("Finished");
        Console.In.ReadLine();
    }
}

At first I had the problem described here but then I tried to run the program outside Visual Studio I got a "Program has stopped responding" error.


Solution

  • Wanted to add my own findings here as the behavior here is certainly strange - and as such, the accepted answer is not entirely correct.

    Given the following sample:

    static void Main(string[] args)
    {
        try{
            throw new Exception("");
        } finally {
            Console.WriteLine("I am never called!");
            Console.ReadLine();
        }
    }
    
    

    The finally block is actually executed IF we choose to CANCEL out of the Windows Error Reporting Dialog, as such:

    Windows Error Reporting In Progress Console After Done

    HOWEVER, if we allow the Windows Error Reporting Dialog to "complete", so we get the option to "Debug" or "Close Program", then the finally block is NOT executed.

    enter image description here enter image description here


    Which to me indicates that the .NET Runtime WILL actually run all finally blocks, regardless of experiencing a "Unhandled top level Exception", and that what's preventing it from doing so is actually Windows (if you select "Close Program") or the Visual Studio Debugger (if you select "Debug" or is starting with the debugger attached)... As they kill the process before the Runtime as a chance to proceed.

    Any thoughts?