سؤال

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.'

هل كانت مفيدة؟

المحلول 2

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"

نصائح أخرى

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

It's possible that you are debugging and when you click no, the execution is being halted by the debugger.

When running from command line. Just when Windows tries to end application gracefully click no or cancel if application is not responding. enter image description here

An exception bubbles up the stack until it finds a handler. If it doesn't, the program exits. That's the case in your scenario... there's no handler, so the program exits before it hits the finally block.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top