学习AppDomain. UnhandledException
- 命名空间:System
当一个异常(Exception)没有被捕获时引发这个事件。
引用官方帮助的一个例子来说明1:
using System;
using System.Security.Permissions;
public class Example
{
[SecurityPermission(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlAppDomain)]
public static void Main()
{
// 取当前作用域
AppDomain currentDomain = AppDomain.CurrentDomain;
// 当前作用域出现未捕获异常时,使用MyHandler函数响应事件
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
try {
// 这里直接抛出异常
throw new Exception("1");
} catch (Exception e) {
// 异常1会被这个catch捕获
Console.WriteLine("Catch clause caught : {0} \n", e.Message);
}
// 这里再抛出异常2,但没有进行捕获。它会引发UnhandledException事件
throw new Exception("2");
}
// 我们已经设置了这个函数响应UnhandledException事件,抛出异常2后,会调用此函数
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception) args.ExceptionObject;
Console.WriteLine("MyHandler caught : " + e.Message);
Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
}
}
// 这个例程的输出为:
// Catch clause caught : 1
//
// MyHandler caught : 2
// Runtime terminating: True
//
// Unhandled Exception: System.Exception: 2
// at Example.Main()
注意,这个异常虽然触发了事件并设置了响应函数,但还是没有处理异常。即,程序还会中断。