如何捕获全局异常
不用多说,直接看代码:
static class Program { private static System.Threading.Mutex mutex; /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { try { //设置应用程序处理异常方式:ThreadException处理 Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); //处理UI线程异常 Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); //处理非UI线程异常 AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frMain()); } catch(Exception ex) { string str = GetExceptionMsg(ex, string.Empty,true); MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } //处理UI线程异常 static void Application_ThreadException(object sender,System.Threading.ThreadExceptionEventArgs e) { string str = GetExceptionMsg(e.Exception, e.ToString(),false); CommDlg.SaveExceptionLog(str); } //处理非UI线程异常 static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { /* * 在 app.config 文件的 <runtime> 节点中添加如下代码: * <legacyUnhandledExceptionPolicy enabled="1"/> * 加上了这个配置之后,Appdomain.CurrentDomain.UnhandledException 事件的 IsTerminating 就变成了 false 啦! * 也就是说,程序并不会因为这次的异常而崩溃退出。 */ string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString(),true); CommDlg.SaveExceptionLog(str); } static string GetExceptionMsg(Exception ex, string backStr,bool IsThread) { StringBuilder sb = new StringBuilder(); if (IsThread == true) { sb.AppendLine("****************************非UI线程异常****************************"); } else { sb.AppendLine("****************************UI线程异常****************************"); } sb.AppendLine("【出现时间】:" + DateTime.Now.ToString()); if (ex != null) { sb.AppendLine("【异常类型】:" + ex.GetType().Name); sb.AppendLine("【异常信息】:" + ex.Message); sb.AppendLine("【堆栈调用】:" + ex.StackTrace); sb.AppendLine("【异常方法】:" + ex.TargetSite); } else { sb.AppendLine("【未处理异常】:" + backStr); } sb.AppendLine("***************************************************************"); return sb.ToString(); } }
其中要注意的是,要处理UI线程异常,需要绑定 ThreadException 事件:
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
要处理非UI线程异常,需要绑定 UnhandledException 事件:
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
正常情况下,捕获异常后,程序不会崩溃,可以继续执行,当时如果是 非UI线程 的异常,就算捕获了还是会崩溃并退出。
如果需要实现崩溃不退出,需要做以下设置:
在 app.config 文件的 <runtime> 节点中添加如下代码: <legacyUnhandledExceptionPolicy enabled="1"/> 加上了这个配置之后,Appdomain.CurrentDomain.UnhandledException 事件的 IsTerminating 就变成了 false 啦! 也就是说,程序并不会因为这次的异常而崩溃退出。
但是千万要注意,如果开启这个参数,就要确保你的程序处理异常时能排除完再继续执行,否则一味的屏蔽异常只能让你的程序处理万劫不复之地。
注:以上代码只在 .net 4.0 环境下测试,其它版本还没测试过。