一、ThreadException和unhandledException的区别
处理未捕获的异常是每个应用程序起码有的功能,C#在AppDomain提供了UnhandledException 事件来接收未捕获到的异常的通知。常见的应用如下:
static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); } static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Exception error = (Exception)e.ExceptionObject; Console.WriteLine("MyHandler caught : " + error.Message); } |
未捕获的异常,通常就是运行时期的BUG,于是我们可以在UnhandledException 的注册事件方法CurrentDomain_UnhandledException中将未捕获异常的信息记录在日志中。值得注意的是,UnhandledException提供的机制并不能阻止应用程序终止,也就是说,CurrentDomain_UnhandledException方法执行后,应用程序就会被终止。
上面我们举的例子来自于控制台程序,UnhandledException可以在任何应用程序域中使用,在某些应用程序模型,如windows窗体程序,还存在ThreadException来处理 Windows 窗体线程中所发生的其未经处理的异常。即,在windows窗体程序中,使用 ThreadException 事件来处理 UI 线程异常,使用 UnhandledException 事件来处理非 UI 线程异常。ThreadException可以阻止应用程序终止。具体使用方法如下:
[STAThread] static void Main() { Application.ThreadException += new ThreadExceptionEventHandler(UIThreadException); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.Run(new ErrorHandlerForm()); } private static void UIThreadException(object sender, ThreadExceptionEventArgs t) { try { string errorMsg = "Windows窗体线程异常 : \n\n"; MessageBox.Show(errorMsg + t.Exception.Message + Environment.NewLine + t.Exception.StackTrace); } catch { MessageBox.Show("不可恢复的Windows窗体异常,应用程序将退出!"); } } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { try { Exception ex = (Exception)e.ExceptionObject; string errorMsg = "非窗体线程异常 : \n\n"; MessageBox.Show(errorMsg + ex.Message + Environment.NewLine + ex.StackTrace); } catch { MessageBox.Show("不可恢复的非Windows窗体线程异常,应用程序将退出!"); } } |