捕获当前线程的方法:Application.ThreadException
例如:
static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.ThreadException += Application_ThreadException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FrmMain()); } private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) { Exception ex = e.Exception; var msg=string.Format("捕获到未处理异常:{0}\r\n异常信息:{1}\r\n异常堆栈:{2}", ex.GetType(), ex.Message, ex.StackTrace); MessageBox.Show(msg); } }
子线程异常捕获AppDomain.CurrentDomain.UnhandledException
例如:
static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.ThreadException += Application_ThreadException; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FrmMain()); } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Exception ex = e.ExceptionObject as Exception; var msg=string.Format("捕获到未处理异常:{0}\r\n异常信息:{1}\r\n异常堆栈:{2}", ex.GetType(), ex.Message, ex.StackTrace); MessageBox.Show(mst); } private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) { Exception ex = e.Exception; var msg=string.Format("捕获到未处理异常:{0}\r\n异常信息:{1}\r\n异常堆栈:{2}", ex.GetType(), ex.Message, ex.StackTrace); MessageBox.Show(msg); } }
这样在代码内没有捕获的错误,会在系统外面统一捕获到.
不过显示使用中,底层有些错误也会捕获不到,非常少