学习AppDomain. UnhandledException

学习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()  

注意,这个异常虽然触发了事件并设置了响应函数,但还是没有处理异常。即,程序还会中断。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值