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

NET环境下的未处理异常(unhandled exception)的解决方案的更多相关文章

  1. 在windows环境下运行compass文件出现的错误提示解决方案

    在windows环境下运行compass文件出现的错误提示解决方案 例如:经常在项目中运行grunt命令编译scss文件的时候,会出现下面的错误提示 (Encoding::CompatibilityE ...

  2. 项目部署到liunx环境下访问接口返回异常

    1.访问接口返回异常 已经连续踩了两次这个坑了.所以记下来了.方便下次搜索! 项目在window下运行正常,无任何异常! 但是部署到liunx环境下的服务器上就有问题 访问静态页面毫无问题,一旦涉及到 ...

  3. Win32环境下的程序崩溃异常定位

    1       案例描述 作为Windows程序员,平时最担心见到的事情可能就是程序发生了崩溃(异常),这时Windows会提示该程序执行了非法操作,即将关闭.请与您的供应商联系.呵呵,这句微软的“名 ...

  4. 在eclipse环境下使用maven install 命令碰到native2ascii-utf8问题解决方案

    报错语句:Failed to execute goal org.codehaus.mojo:native2ascii-maven-plugin:1.0-beta-1:native2ascii (nat ...

  5. win10环境下pyinstaller打包pytorch遇到的问题及解决方案

    pytorch-python源码生成windows的应用程序(.exe),报错OSError: could not get source code Failed to execute script h ...

  6. [VS2015].NET4.0环境下使用.NET2.0程序集,使用sqlite时报异常 出现“混合模式程序集异常”

    在.net 4.0环境下使用sqlite时报异常 混合模式程序集是针对“v2.0.50727”版的运行时生成的,在没有配置其他信息的情况下,无法在 4.0 运行时中加载该程序集其调用的方法是从sqli ...

  7. WPF捕获全局未处理异常

    在WPF开发过程中我们一般都用try/catch块来捕获异常,但不是每个异常我们都能捕获,程序总会出现一些意想不到情况,抛出一些未捕获的异常,这时就要用到全局异常捕获,即在程序的最外层加上捕获未处理异 ...

  8. Win8 x64环境下VS2010 C#工程运行报错:没有注册类 (异常来自 HRESULT:0x80040154

    来源:http://blog.sina.com.cn/s/blog_7095482001019c2v.html 问题描述: 在Win8 x64环境下,VS2010的C#工程中引用了COM组件(Acti ...

  9. atitit.js浏览器环境下的全局异常捕获

    atitit.js浏览器环境下的全局异常捕获 window.onerror = function(errorMessage, scriptURI, lineNumber) { var s= JSON. ...

随机推荐

  1. [Bhatia.Matrix Analysis.Solutions to Exercises and Problems]ExI.1.3

    Use the QR decomposition to prove Hadamard's inequality: if $X=(x_1,\cdots,x_n)$, then $$\bex |\det ...

  2. Selenium WebDriver + Grid2 + RSpec之旅(四) ----通过RSpec编写测试用例

    Selenium WebDriver + Grid2 + RSpec之旅(四) ----通过RSpec编写测试用例 自动化测试和手工测试一样,是要有测试用例,有检查点和测试结果的,接下来我们通过RSp ...

  3. linux下的oracle11gR2静默安装,经验分享

    说明: 1.我的linux是64位的redhat6.5,安装的oracle版本是11.2.0的. 2.我这是自己安装的linux虚拟机,主机名为ora11g,ip为192.168.100.122 3. ...

  4. 如何使用 RDP 或 SSH 连接到 Azure 虚拟机

    使用 RDP 或 SSH 连接到 Azure 虚拟机 本文简要概述了如何使用远程桌面控制协议 (RDP) 或安全外壳(Secure Shell,SSH)客户端登录 Azure 虚拟机.它还包括要求和故 ...

  5. c++学习_2

    这里承接上一篇文章,继续记录关于继承的那些事儿... NVI(non-Virtual Interface)和strategy模式 NVI模式和strategy模式是两种不同的方法,可以用来替代virt ...

  6. HOG特征

    HOG(Histogram of gradient)统计图像局部区域的梯度方向信息来作为该局部图像区域的表征.HOG特征具有以下几个特点: (1)不具有旋转不变性(较大的方向变化),实际应用中不变性是 ...

  7. C语言之Static

    1.全局静态变量 在全局变量之前加上关键字static,全局变量就被定义成为一个全局静态变量. 1)内存中的位置:静态存储区(静态存储区在整个程序运行期间都存在) 2)初始化:未经初始化的全局静态变量 ...

  8. Dynamics CRM 2011 2013-(An error occurred while opening mailbox xxx@xx.com Microsoft.Crm.Tools.Email.Providers.)

    An error occurred while opening mailbox  Microsoft.Crm.Tools.Email.Providers. Whenever I check how C ...

  9. openstack 虚拟机流量

  10. 几年的Git使用技巧总结

    用git有一年了,下面是我这一年来的git使用总结,覆盖了日常使用中绝大多数的场景.嗯,至少是够用一年了,整理出来分享给大家,不明白的地方可以回复交流. 创建和使用git ssh key 首先设置gi ...