WPF 捕捉全局異常


public App()
        {
            //首先注冊開始和退出事件
            this.Startup += new StartupEventHandler(App_Startup);
            this.Exit += new ExitEventHandler(App_Exit);
        }

        void App_Startup(object sender, StartupEventArgs e)
        {
            //UI線程未捕獲異常處理事件
            this.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(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類里面 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM