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询问我是否要结束应用,我说'是'.
当您收到“ConsoleApplication1”已停止响应时,您有两种选择。

如果您按“取消”,则允许未处理的异常继续,直到应用程序最终终止。这允许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)
总是给出输出“最后”