通常我們在寫程序時會對程序中可能出錯的程序段用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(); } } } }