通常我们在写程序时会对程序中可能出错的程序段用try catch 捕捉获取。这样程序运行中一旦有bug。用户也能快速定位到错误段去了解出错原因。
遇到的问题: 但是遇到这样的情况 有时候没有用到try catch 时出错了。程序直接停止响应。这时候对于开发人员就比较伤脑筋。无法快速debug
C#程序如何捕捉未try/catch的异常——不弹“XXX已停止工作”报错框?
解决方法:
1:在Main主程序中添加代码 设置 Windows 窗体线程和其他线程上发生的异常发生异常的事件处理的程序。使用 ThreadException 事件处理 UI 线程异常和 UnhandledException事件来处理非 UI 线程异常。一般ui线程异常会有MessageBox显示, 这里就不写相应代码。详见MSDN :https://msdn.microsoft.com/zh-cn/library/ms157905(v=vs.110).aspx
当运行程序出现停止响应后,在程序跟目录下的ErrLog文件夹的ErrLog.txt会记录下错误信息和位置。方便查看
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms;namespace WindowsFormsApplication3 {static class Program{/// <summary>/// 应用程序的主入口点。/// </summary> [STAThread]static void Main(){Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);//添加非UI上的异常.AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(new Form1());}private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e){try{Exception ex = (Exception)e.ExceptionObject;WriteLog(ex.Message + "\n\nStack Trace:\n" + ex.StackTrace);}catch (Exception exc){try{MessageBox.Show(" Error"," Could not write the error to the log. Reason: "+ exc.Message, MessageBoxButtons.OK, MessageBoxIcon.Stop);}finally{Application.Exit();}}}static void WriteLog(string str){if (!Directory.Exists("ErrLog")){Directory.CreateDirectory("ErrLog");}string fileName = DateTime.Now.ToString("yyyy-MM-dd")+"ErrLog.txt";using (var sw = new StreamWriter(@"ErrLog\" + fileName, true)){sw.WriteLine("***********************************************************************");sw.WriteLine(DateTime.Now.ToString("HH:mm:ss"));sw.WriteLine(str);sw.WriteLine("---------------------------------------------------------");sw.Close();}}} }