.Net 下未捕获异常的处理

来源:互联网 发布:123d打印软件 编辑:程序博客网 时间:2024/06/01 08:26

   在开始本文之前,让我们来看看.Net在什么情况下会产生未捕获异常。未捕获异常从定义上说就是结构化异常处理未能捕获的异常。通俗的讲就是发生在Try Catch块意外的异常。那么是不是我们在Main函数中加一个Try Catch 块就可以捕获全部未捕获异常了呢?答案是否定的。这里面有两种情况无法通过这种方法捕获:

1. GC 产生的异常,这种异常通常因为Finalize函数中引发未捕获异常引起。当然这并不绝对,一些系统问题比如内存耗尽有时候也会造成GC异常。 

2. 主线程以为的线程引发的未捕获异常。这些异常我们往往可以在线程的主函数中用Try Catch 来捕获,但如果系统中使用了外部的组件,或者甚至是.Net 框架自带的一些系统组件,由这些组件的线程引发的异常,调用代码无法通过Try Catch来捕获。

从上面两点来看,即使我们的代码在每个地方都加了Try Catch ,也不能百分百杜绝未捕获异常的发生。 

鉴于此,为了提高系统的健壮性和可维护性,我们需要通过一种方法来截获这些未捕获异常,并进行适当的处理。

.Net 的设计者已经考虑到这些问题,并且为我们提供了一个叫 UnhandledExceptionEventHandler 的事件,通过这个事件,我们可以截获未捕获异常,并进行处理。

这个事件的事件参数UnhandledExceptionEventArgs e, 有两个属性,一个是ExceptionObject,这个属性返回为截获异常的对象实例。还有一个属性是IsTerminating,这个属性告诉我们这个异常是否会导致应用终止。这里需要说明的是,对于.Net1.1 和 .Net2.0及以上,情况是不一样的,.Net1.1 只有在主线程中的未捕获异常才会终止应用程序,而.Net2.0及以上版本则是始终终止应用程序。如果不终止应用程序,而是有CLR 将当前异常消化,系统的运行状态很可能不可控,最后可能会发生更大的故障,所以.Net2.0以后,对于所有未捕获异常,一律终止当前应用。这样看来,对于.net2.0以上的应用似乎我们截获未捕获异常已经毫无意义,其实不然。通过截获为未捕获异常,我们可以记录下程序是再哪里产生这种未捕获异常的,以便程序的开发者改进程序。我们也可以在当前应用退出前为系统做一些其他的保护工作,比如备份数据,告警提示等等。

下面我们来看看三种常见的.Net应用分别如何来截获未捕获异常。

  • 控制台应用

     首先为当前AppDomain 添加  UnhandledExceptionEventHandler

AppDomain.CurrentDomain.UnhandledException +=              new UnhandledExceptionEventHandler(UnhandledExceptionEventHandler);

再添加事件响应函数

static void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e)        {            try            {                using (System.IO.FileStream fs = new System.IO.FileStream(@"c:\testme.log",                          System.IO.FileMode.Append, System.IO.FileAccess.Write))                {                    using (System.IO.StreamWriter w = new System.IO.StreamWriter(fs,                              System.Text.Encoding.UTF8))                    {                        w.WriteLine(e.ExceptionObject);                    }                }            }            catch            {            }        }

现在我们就可以截获未捕获异常了

下面是完整的测试代码:

public class TestRaiseException        {            ~TestRaiseException()            {                int i = 0;                int j = 1 / i;            }        }        static void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e)        {            try            {                using (System.IO.FileStream fs = new System.IO.FileStream(@"c:\testme.log",                      System.IO.FileMode.Append, System.IO.FileAccess.Write))                 {                    using (System.IO.StreamWriter w = new System.IO.StreamWriter(fs,                          System.Text.Encoding.UTF8))                     {                        w.WriteLine(e.ExceptionObject);                    }                }            }            catch            {            }        }        static void Main(string[] args)        {            AppDomain.CurrentDomain.UnhandledException +=                     new UnhandledExceptionEventHandler(UnhandledExceptionEventHandler);              TestRaiseException testRaiseException = new TestRaiseException();        }

 程序运行后记录下日志如下

System.DivideByZeroException: Attempted to divide by zero.
   at TestCosole.Program.TestRaiseException.Finalize() 

 

  • WinForm

    WinForm 应用通过 Application.ThreadException 事件来截获未捕获异常

  详见 园子里面另一篇博客,这里就不再冗诉。

     体面地处理程序的未捕获异常

  • Asp.net

     ASP.NET 应用和前两种应用有所不同,ASP.NET 一般在后台线程或者线程池中产生未捕获异常,才会导致W3WP.exe终止,并在事件查看器中产生一条类似下面内容的事件:EventType clr20r3, P1 w3wp.exe, P2 6.0.3790.1830, P3 42435be1, P4 app_web_ncsnb2-n, P5 0.0.0.0, P6 440a4082, P7 5, P8 1, P9 system.nullreferenceexception, P10 NIL. 

     要截获ASP.NET 的未捕获异常,我们需要为每个应用程序域安装事件钩子

     这个过程需要分两步完成:

     首先创建一个实现IHttpModule接口的类 

using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;namespace WebMonitor{    /**//// <summary>    /// Summary description for UnhandledExceptionModule    /// </summary>    public class UnhandledExceptionModule : IHttpModule    {        static object _initLock = new object();        static bool _initialized = false;        public UnhandledExceptionModule()        {            //            // TODO: Add constructor logic here            //        }        void OnUnhandledException(object o, UnhandledExceptionEventArgs e)        {            //Do some thing you wish to do when the Unhandled Exception raised.            try            {                using (System.IO.FileStream fs = new System.IO.FileStream(@"c:\testme.log",                         System.IO.FileMode.Append, System.IO.FileAccess.Write))                 {                    using (System.IO.StreamWriter w = new System.IO.StreamWriter(fs, System.                            Text.Encoding.UTF8))                     {                        w.WriteLine(e.ExceptionObject);                    }                }            }            catch            {            }        }        IHttpModule Members#region IHttpModule Members        public void Dispose()        {            throw new Exception("The method or operation is not implemented.");        }        public void Init(HttpApplication context)        {            // Do this one time for each AppDomain.            lock (_initLock)            {                if (!_initialized)                {                    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);                    _initialized = true;                }            }        }        #endregion    }}

 第二步:

 修改web.config

在 system.web 段中加入

    <httpModules>      <add name="UnhandledExceptionModule" type="WebMonitor.UnhandledExceptionModule" />          </httpModules>

 完成这两步后,你的ASP.NET 应用就可以截获未捕获异常了。

 下面是测试代码

using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partial class _Default : System.Web.UI.Page {    protected void Page_Load(object sender, EventArgs e)    {    }    protected void TestMe(object state)    {        byte[] buf = new byte[2];        buf[2] = 0;    }    protected void Button1_Click(object sender, EventArgs e)    {        System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(TestMe),                   null);      }}

 按下Button1后,w3wp.exe被终止,testme.log 中记录下了异常信息如下:

System.IndexOutOfRangeException: Index was outside the bounds of the array.

   at _Default.TestMe(Object state) in c:"ApolloWorkFolder"test"laboratory

"TestWebSite"Default.aspx.cs:line 21

   at System.Threading._ThreadPoolWaitCallback.WaitCallback_Context(Object state)
   at System.Threading.ExecutionContext.runTryCode(Object userData)

   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(

TryCode code, CleanupCode backoutCode, Object userData)

   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,

ContextCallback callback, Object state)

   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,

ContextCallback callback, Object state)

   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal(

_ThreadPoolWaitCallback tpWaitCallBack)

   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(Object state)




原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 支付宝验证码被别人知道了怎么办 微信解除银行卡绑定零钱清零怎么办 qq号被盗了理财通的钱怎么办 工行转错账号的钱被冻结怎么办 微信20w限额满了怎么办 通过qq号申请微信被盗了怎么办 微信号被盗手机绑定被改怎么办 腾讯视频激活码兑换达到限制怎么办 虚拟服务购买自动每月扣q币怎么办 微信被骗充值Q币怎么办 微信给别人充q币怎么办 k歌别人送的k币怎么办 忘记了qq号码但记得密码怎么办 q自己的活干完了该怎么办 在应用宝下载的游戏搜不到了怎么办 衣服有图片在淘宝找不到同款怎么办 淘宝卖家小儿说质量不合格怎么办 订单显示显示已签收没收到货怎么办 网上买过的东西查不到订单号怎么办 亚航的组合机票飞机延误怎么办 在微信上面对面红包被骗了钱怎么办 人欠我钱不给我怎么办 微信号被骗走然后骗了朋友钱怎么办 微信手机充值不到帐怎么办 中银香港密码器坏了怎么办 香港恒生银行的编码器丢了怎么办 淘宝拍下订单发货物流不显示怎么办 wish查到仿品审核变慢怎么办 淘宝卖家订单号错误无法修改怎么办 顺丰快递运单号微信扫描取消怎么办 买的王者荣耀号有守护平台怎么办 融e联登录密码错三次怎么办 金融e家u盾密码忘了怎么办 用工行网银转账后想取消交易怎么办 工行融e借没有密码器怎么办 工行融e借密码器丢了怎么办 工行融e联手机登录密码忘记怎么办 领导给员工抱怨工作太烦怎么办 员工抱怨忙的忙死闲的闲死怎么办 爱上骗我进传销的人该怎么办 尚赫辟谷期间吃了东西怎么办