WPF处理未捕获的异常

程序中难免会有各种异常产生,为了程序稳定,在各种可能发生异常的地方都要进行捕获操作,将异常进行各种处理,但总是难免会有漏网之鱼。一旦有这种漏网的异常发生,程序可能马上崩溃。

WPF提供了Application.DispatcherUnhandledException 事件,如果应用程序引发异常半且未处理则引发此事件。因此可以在此事件中对异常进行处理。

// 程序启动时注册DispatcherUnhandledException事件
        protected override void OnStartup(StartupEventArgs e)
        {

            Current.DispatcherUnhandledException += AppDispatcherUnhandledException;
            base.OnStartup(e);
        }

        protected override void OnExit(ExitEventArgs e)
        {
            Current.DispatcherUnhandledException -= AppDispatcherUnhandledException;
            base.OnExit(e);
        }

        private void AppDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            //设置异常已处理
            e.Handled = true;
            //异常处理
            new ExceptionViewModel(e.Exception);
        }

ExceptionViewModel用于显示具体的错误信息。

测试

private void exceptionButton_Click(object sender, RoutedEventArgs e)
        {
            throw new Exception("按键引发的异常");
        }


        private void delFileButton_Click(object sender, RoutedEventArgs e)
        {
            Directory.Delete(@"c:\wmm"); //c:/wmm不存在即引发异常
        }

手动引发异常

 

未捕获的异常

posted on 2013-05-10 21:38  太阳下的蛋  阅读(515)  评论(0编辑  收藏  举报