標籤:could not 解決方案 已停止工作 text hex sts 應用 led 資訊
通常我們在寫程式時會對程式中可能出錯的程式段用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(); } } }}
Winform程式當運行exe 停止回應時 如何記錄下日誌?