简而言之,MSDN描述了用户模式应用程序的异常调度,如下所示:
- 调试器会收到第一次出现异常的通知(如果附加)
- 一个异常处理程序。调用
try/catch
(如果可用) - 调试器会收到第二次机会异常的通知(如果已附加)
- 系统关心未处理的异常(通常:终止进程)
此序列不考虑是否存在未处理的异常处理程序。当存在未处理的异常处理程序时,异常调度如何更改?
未处理的异常处理程序插入位置3。顺序为:
- 调试器会收到第一次出现异常的通知(如果附加)
- 一个异常处理程序。调用
try/catch
(如果可用) - 调用未处理的异常处理程序(注意复数)(如果可用)
- 调试器会收到第二次机会异常的通知(如果已附加)
- 系统关心未处理的异常(通常:终止进程)
下面的C#程序演示了它。NET版本,您将收到另一个未处理的异常处理程序的消息,该异常处理程序是。NET框架打印异常和调用堆栈。
using System;
namespace UnhandledException
{
static class Program
{
static void Main()
{
Console.WriteLine("Please attach the debugger now and press Enter.");
Console.ReadLine();
AppDomain.CurrentDomain.UnhandledException += (sender, e) => Unhandled1();
AppDomain.CurrentDomain.UnhandledException += (sender, e) => Unhandled2();
try
{
Console.WriteLine("Throwing now.");
// Will cause a first chance, because in try/catch
throw new Exception("Any exception will do");
}
catch (Exception)
{
// Will cause first chance and second chance, because in NOT try/catch
Console.WriteLine("In catch block.");
throw;
}
}
static void Unhandled1() => Console.WriteLine("In unhandled exception handler 1");
static void Unhandled2() => Console.WriteLine("In unhandled exception handler 2");
}
}
调试器(WinDbg)中所需的命令:
.symfix
.reload
sxe clr
g; *** for the breakpoint due to attaching the debugger
g; *** first chance in try/catch
g; *** first chance outside try/catch
g; *** second chance