WPF记录(一)——App中捕获整个程序的异常

App中捕获整个程序的异常

 

一、DispatcherUnhandledExceptionEventHandler 事件

        // 摘要:
        //     ,如果异常是由应用程序引发,但未处理,发生。
        public event DispatcherUnhandledExceptionEventHandler DispatcherUnhandledException;

 

二、在app.xaml.cs中注册事件

 protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            //注册Application_Error
            this.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);

        }

        //异常处理逻辑
        void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            MessageBox.Show("有未处理的异常:" + e.Exception.Message);
            //处理完后,我们需要将Handler=true表示已此异常已处理过
            e.Handled = true;
        }

委托 DispatcherUnhandledExceptionEventHandler 名称空间为 System.Windows.Threading

三、测试

     添加Button按钮,在Click事件处理程序下主动抛出异常

 private void Button_Click(object sender, RoutedEventArgs e)
        {
            
            throw new Exception("抛出异常测试");
        }

 

posted @ 2020-05-25 15:27  流沙河小妖  阅读(172)  评论(0编辑  收藏  举报