Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the finally getting executed?

It was my assumption that the finally block always gets executed as long as the program is running. However, in this console app, the finally block does not seem to get executed.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                throw new Exception();
            }
            finally
            {
                Console.WriteLine("finally");
            }
        }
    }
}

Output

Result

Note: When the exception was thrown, windows askmed me if I wanted to end the appliation, I said 'Yes.'

like image 830
Anish Avatar asked Jan 10 '13 16:01

Anish


2 Answers

It executed actually. Just you didn't notice. Just when you see Windows is checking for a solution to the problem click Cancel and see it.

enter image description here

like image 186
Soner Gönül Avatar answered Sep 29 '22 11:09

Soner Gönül


When you get the "ConsoleApplication1" has stopped responding, you have two choices.

Windows Error Reporting dialog

If you press cancel, the unhandled exception is allowed to continue until eventually the application is terminated. This allows the finally block to execute. If you do not press cancel then Windows Error Reporting halts the process, collects a minidump and then terminates the application. This means the finally block is not executed.

Alternatively, if you handle the exception in a higher method you will definitely see the finally block. For example:

static void unhandled()
{
    try
    {
        throw new Exception();
    }
    finally
    {
        Console.WriteLine("finally");
    }
}

static void Main(string[] args)
{
    AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
    try
    {
        unhandled();
    }
    catch ( Exception )
    {
        // squash it
    }
}

Always gives the output "finally"

like image 29
Steve Avatar answered Sep 29 '22 10:09

Steve