有时在软件开发客户使用时会遇到莫名闪退,搞得异常都不好分析,下面介绍一种捕获整个程序的异常的方法,可以放在Program中,软件异常时可以有详细的记录:
Main主函数
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);//捕获主线程的异常 AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);//捕获子线程的异常
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Exception ex = e.ExceptionObject as Exception; MessageBox.Show(string.Format("捕获到未处理异常:{0}rn异常信息:{1}rn异常堆栈:{2}rnCLR即将退出:{3}-true退出 false不退出",ex.GetType(), ex.Message, ex.StackTrace, e.IsTerminating)); } static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) { Exception ex = e.Exception; MessageBox.Show(string.Format("捕获到未处理异常:{0}rn异常信息:{1}rn异常堆栈:{2}",ex.GetType(), ex.Message, ex.StackTrace)); }
异常也可以写入文件记录中
声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!