我希望防止出现异常时出现“应用程序已停止工作”弹出窗口。一种方法显然是调用Environment.Exit(1)
全局异常处理程序,即AppDomain.CurrentDomain.UnhandledException
像这样:
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception exc = (Exception)e.ExceptionObject;
Console.Error.WriteLine("Exception:\n{0}", exc.Message);
Console.Error.WriteLine("Stack trace:\n{0}", exc.StackTrace);
Environment.Exit(1); // quit silently on exception, don't show the popup
}
但是,由于执行顺序,上述代码导致finally
块未执行。这种行为的一个简单示例:
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
try
{
Console.WriteLine("try block");
throw new Exception("Somebody set us up the bomb.");
}
catch
{
Console.Error.WriteLine("catch block");
throw;
}
finally
{
Console.WriteLine("finally block");
}
Environment.Exit(1)
在应用程序退出之前,异常处理程序会导致此输出(注意没有 finally 块):
try block
catch block
Exception:
Somebody set us up the bomb.
Stack trace:
at ...
当块执行至关重要finally
时,例如清理内部创建的临时文件时,这可能会导致严重问题try
。
有没有一种简单的方法来解决这一切?也就是说,在其中保留全局异常处理程序、自定义异常输出等,然后优雅地退出,但仍然得到finally
要执行的块。我觉得奇怪的是,在这样的问题中没有提到这个问题。