6

我的假设是只要程序正在运行,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");
            }
        }
    }
}

输出

结果

注意:当抛出异常时,windows 询问我是否要结束应用程序,我说“是”。

4

5 回答 5

6

它实际上执行了。只是你没有注意到。只是当你看到Windows is checking for a solution to the problem点击Cancel并看到它。

在此处输入图像描述

于 2013-01-10T16:38:09.837 回答
2

您可能正在调试,当您单击“否”时,调试器正在暂停执行。

于 2013-01-10T16:38:32.277 回答
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
    }
}

总是给出“最后”的输出

于 2013-01-10T17:24:01.673 回答
1

从命令行运行时。就在 Windows 尝试优雅地单击结束应用程序nocancel应用程序没有响应时。 在此处输入图像描述

于 2013-01-10T16:39:30.513 回答
-2

异常会在堆栈中冒泡,直到找到处理程序。如果没有,则程序退出。在您的场景中就是这种情况......没有处理程序,因此程序在到达 finally 块之前退出。

于 2013-01-10T16:40:07.383 回答