zoukankan      html  css  js  c++  java
  • NET环境下的未处理异常(unhandled exception)的解决方案

    NET环境下的未处理异常(unhandled exception )的解决方案

         .Net 框架提供了非常强大的异常处理机制,同时对一些非托管代码很难控制的系统问题比如指针越界,内存泄漏等提供了很好的解决方案。相比非托管代码构建的系 统,.Net构建的系统更加稳定。不过这并不是说.Net构建的系统就完全无懈可击,很多由于代码的不严谨或者系统问题引发的故障将会导致.Net应用程 序产生未捕获异常,从而导致应用程序异常终止。

          本文将对三种最常见的.Net应用的未捕获异常处理进行阐述。

          在开始本文之前,让我们来看看.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 
         } 
     } 

     第二步:

     修改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)。

    一份耕耘,一份收获,付出就有回报永不遭遇过失败,因我所碰到的都是暂时的挫折
  • 相关阅读:
    显示屏分辨率自动调整例子
    该内存不能read 或written数值 叙述
    DELPHI之关于String的内存分配(引)
    Delphi关于记录文件的操作转
    用句柄操作下拉框
    SendMessage参数
    c#通过SendMessage发送消息
    Delphi内存专题 (引)
    Delphi7 中使用ODAC存取图片
    打印机状态测试
  • 原文地址:https://www.cnblogs.com/raincedar/p/5577843.html
Copyright © 2011-2022 走看看