.Net下Unhandled Exception的捕获

C# 处理unhandled Exception方式如下:

  1. 在程序的Main()方法中增加如下代码。
    <pre>//处理线程未处理的异常
    Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
    //处理系统未处理的异常
    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
    //运行程序
    Application.Run(new frmServerMain());
    </pre>
  2. 方法:
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            string str = "";
            Exception error = e.Exception as Exception;
            if (error != null)
            {
                str = string.Format("Application unhandled exception.\nExceptionType:{0}\nException Message: {1}\n StackTrace:{2}\n",
                     error.GetType().Name, error.Message, error.StackTrace);
            }
            else
            {
                str = string.Format("Application Thread Exception Msg:{0}", e);
            }
            WriteErrInfo(str);
        }
       static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string str = "";
            Exception error = e.ExceptionObject as Exception;
            if (error != null)
            {
                str = string.Format("Application UnhandledException:{0};\nStackTrace:{1}", error.Message, error.StackTrace);
            }
            else
            {
                str = string.Format("Application UnhandledError:{0}", e);
            }
            WriteErrInfo(str);
        }
        static void WriteErrInfo(string vErrMsg)
        {
            using (System.IO.FileStream fs = new System.IO.FileStream(Application.StartupPath + "\\Log\\TestException.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(vErrMsg); DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                }
            }
        }

详细分析可参见:
http://www.cnblogs.com/eaglet/archive/2009/02/17/1392191.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,288评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,877评论 18 399
  • 不支持上传文件,所以就复制过来了。作者信息什么的都没删。对前端基本属于一窍不通,所以没有任何修改,反正用着没问题就...
    全栈在路上阅读 2,018评论 0 2
  • 2017年3月22日 回首去年的心路,一直都是体验各种情绪,悲伤、软弱、无力,走出来后不久又掉到情绪和负性思...
    Indigolove阅读 141评论 0 0
  • p2p财富公司排名 p2p财富公司排名 p2p财富公司排名
    沈恫亢86510阅读 1,550评论 0 0