为什么最终没有被执行?

Ani*_*ish 6 .net c# exception try-catch try-finally

我的假设是,只要程序正在运行,finally块就会被执行.但是,在此控制台应用程序中,finally块似乎没有被执行.

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");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

产量

结果

注意:当抛出异常时,Windows询问我是否要结束应用,我说'是'.

Son*_*nül 6

它实际上执行了.只是你没注意到.就在你看到Windows is checking for a solution to the problem点击Cancel并看到它的时候.

在此输入图像描述


Ste*_*eve 2

当您收到“ConsoleApplication1”已停止响应时,您有两种选择。

Windows 错误报告对话框

如果您按“取消”,则允许未处理的异常继续,直到应用程序最终终止。这允许finally块执行。如果您不按“取消”,Windows 错误报告将停止该进程,收集小型转储,然后终止应用程序。这意味着该finally块没有被执行。

或者,如果您在更高的方法中处理异常,您肯定会看到该finally块。例如:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

总是给出输出“最后”