WPF 捕捉全域性異常
阿新 • • 發佈:2018-12-12
public App() { //首先註冊開始和退出事件 this.Startup += new StartupEventHandler(App_Startup); this.Exit += new ExitEventHandler(App_Exit); } void App_Startup(object sender, StartupEventArgs e) { //UI執行緒未捕獲異常處理事件 this.DispatcherUnhandledException += newDispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException); //Task執行緒內未捕獲異常處理事件 TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; //非UI執行緒未捕獲異常處理事件 AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); }void App_Exit(object sender, ExitEventArgs e) { //程式退出時需要處理的業務 } void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { try { e.Handled = true; //把 Handled 屬性設為true,表示此異常已處理,程式可以繼續執行,不會強制退出MessageBox.Show("UI執行緒異常:" + e.Exception.Message); } catch (Exception ex) { //此時程式出現嚴重異常,將強制結束退出 MessageBox.Show("UI執行緒發生致命錯誤!"); } } void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { StringBuilder sbEx = new StringBuilder(); if (e.IsTerminating) { sbEx.Append("非UI執行緒發生致命錯誤"); } sbEx.Append("非UI執行緒異常:"); if (e.ExceptionObject is Exception) { sbEx.Append(((Exception)e.ExceptionObject).Message); } else { sbEx.Append(e.ExceptionObject); } MessageBox.Show(sbEx.ToString()); } void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) { //task執行緒內未處理捕獲 MessageBox.Show("Task執行緒異常:" + e.Exception.Message); e .SetObserved();//設定該異常已察覺(這樣處理後就不會引起程式崩潰) }
使用方法: public partial class App : Application { //複製到App類裡面 }