在.NET中,我们使用try-catch-finally来处理异常。但,当一个Exception抛出,抛出Exception的代码又没有被try包围时,程序就崩溃了。

这些异常往往是你没有注意到的。在WPF中,提供了一种处理这些个异常的方式。

举例来说明。

1.先抛出个异常,不用try包围它。

在MainWindow上添加一个如下的Button。

<Window x:Class="HandlingAnUnhandledException.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<Button Click="OnClick">
<Button.Template>
<ControlTemplate>
<Grid>
<Ellipse Height="100" Width="250" Fill="Pink"/>
<TextBlock Text="Button to Throw Exception by DebugLZQ" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
</StackPanel>
</Window>

在Button的Click事件中抛出个异常

        private void OnClick(object sender, RoutedEventArgs e)
{
throw new InvalidOperationException("Something has gone wrong.");
}

如果,我们Ctrl+F5运行这个程序,点击按钮,程序就崩溃了。
WPF如何解决这个问题呢?

2.WPF处理这种异常的方法

在App.xaml.cs中订阅DispatcherUnhandledException事件,并添加相应的事件处理。

App.xaml.cs如下:

    public partial class App : Application
{
public App()
{
DispatcherUnhandledException += App_DispatcherUnhandledException;
} void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
MessageBox.Show("Error encountered! Please contact support."+ Environment.NewLine + e.Exception.Message);
//Shutdown(1);
e.Handled = true;
}
}

这时,当我们Ctrl+F5运行程序。

这样,异常就被捕获并处理了,程序没有崩溃。

Update:刚百度了一下:WinForm也有类似的机制,请参考Kevin Gao的这篇博文:C# winform 捕获全局异常.

 Update:

  所有 WPF 应用程序启动时都会加载两个重要的线程:一个用于呈现用户界面,另一个用于管理用户界面。呈现线程是一个在后台运行的隐藏线程,因此我们通常面对的唯一线程就是 UI 线程。

  这种方法只能捕捉UI线程的异常,及使用了Dispatcher进行线程关联了的线程(其实Dispatcher.Invoke/BeginInvoke就是将要执行的代码,扔到UI线程去执行)的异常。不能捕捉普通的子线程异常。

如:

private void OnClick(object sender, RoutedEventArgs e)
{
Dispatcher.BeginInvoke(new Action(() => { throw new InvalidOperationException("Something has gone wrong."); }));
}

也可以正常捕获。

而:

private void OnClick(object sender, RoutedEventArgs e)
{
Thread t = new Thread(() => { throw new InvalidOperationException("Something has gone wrong."); });
t.IsBackground = true;
t.Start();
}

则不能捕获。

感谢veboys博友的指点~

------------------------------------------

同样的,即使我们用一个try-catch包围如下的异常,异常也不会被Handle:

try
{
var thread = new Thread(() => {throw new Exception(); });
thread.Start();
}
catch (Exception)
{
MessageBox.Show("Will not execute!");
throw;
}
try
{
Task.Run(() =>{throw new Exception(); });
}
catch (Exception)
{
MessageBox.Show("Will not execute!");
}

--------------

对应Async await 异常:

private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
try
{
await Task.Run(() => { throw new Exception(); });
}
catch (Exception)
{
MessageBox.Show("Will execute!");
}
}

处理Unhandled exception异常 如下:TaskScheduler.UnobservedTaskException

    public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
RegisterEvents();
base.OnStartup(e);
} private void RegisterEvents()
{
TaskScheduler.UnobservedTaskException += (sender, args) =>
{
MessageBox.Show(args.Exception.Message);
args.SetObserved();
}; AppDomain.CurrentDomain.UnhandledException += (sender, args) => MessageBox.Show("Unhandled exception.");
}
}

 Update:

WPF程序的异常捕获总结

WPF整理-处理没有注意到的异常的更多相关文章

  1. WPF整理-Style

    "Consistency in a user interface is an important trait; there are many facets of consistency,   ...

  2. WPF整理-使用用户选择主题的颜色和字体

    “Sometimes it's useful to use one of the selected colors or fonts the user has chosen in theWindows ...

  3. WPF整理-自定义一个扩展标记(custom markup extension)

    "Markup extensions are used to extend the capabilities of XAML, by providing declarativeoperati ...

  4. WPF整理-XAML访问静态属性

    "XAML provides an easy way to set values of properties—type converters and the extended propert ...

  5. WPF整理-XAML构建后台类对象

    1.XAML 接触WPF的第一眼就是XAML---XAML是用来描绘界面的.其实不然! "Actually, XAML has nothing to do with UI. It's mer ...

  6. 捕捉WPF应用程序中XAML代码解析异常

    原文:捕捉WPF应用程序中XAML代码解析异常 由于WPF应用程序中XAML代码在很多时候是运行时加载处理的.比如DynamicResource,但是在编译或者运行的过程中,编写的XAML代码很可能有 ...

  7. 干!一张图整理了 Python 所有内置异常

    在编写程序时,可能会经常报出一些异常,很大一方面原因是自己的疏忽大意导致程序给出错误信息,另一方面是因为有些异常是程序运行时不可避免的,比如在爬虫时可能有几个网页的结构不一致,这时两种结构的网页用同一 ...

  8. 太干了!一张图整理了 Python 所有内置异常

    在编写程序时,可能会经常报出一些异常,很大一方面原因是自己的疏忽大意导致程序给出错误信息,另一方面是因为有些异常是程序运行时不可避免的,比如在爬虫时可能有几个网页的结构不一致,这时两种结构的网页用同一 ...

  9. WPF整理-Mutex确保Application单例运行

    有时我们不希望我们的WPF应用程序可以同时运行有多个实例,当我们试图运行第二个实例的时候,已经运行的实例也应该弹出来. 我们可以用Mutex来实现 打开App.xaml.cs,在App类中添加如下内容 ...

随机推荐

  1. css3 动画的有关属性

    transform transform: none|transform-functions; transform 属性向元素应用 2D 或 3D 转换.该属性允许我们对元素进行旋转.缩放.移动或倾斜. ...

  2. [Android Pro] AsyncTaskLoader vs AsyncTask

    reference to : http://blog.csdn.net/a910626/article/details/45599133 我看了一下asyncTask是从LV3开始,AsyncTask ...

  3. eclipse各版本介绍

    记录下吧!以免以后下载时候又不知道下载那个: Eclipse IDE for Java Developers 是为java开发的 Eclipse IDE for Java EE Developers  ...

  4. java程序性能优化

    一.避免在循环条件中使用复杂表达式 在不做编译优化的情况下,在循环中,循环条件会被反复计算,如果不使用复杂表达式,而使循环条件值不变的话,程序将会运行的更快. 例子: import java.util ...

  5. UML大战需求分析——阅读笔记03

    读<UML大战需求分析>有感03 状态机图和活动图在样子比较相似,但状态机图是用来为对象的状态及造成状态改变的事件建模.我们大二学习UML统一建模语言状态机图模块时了解到,UML的状态机图 ...

  6. SQL语法和运算符(一)

    一个数据库通常包含一个或多个表.每个表由一个名字标识,表包含带有数据的记录(行). 一些最重要的SQL命令(SQL对大小写不敏感): 一.SQL语法 select:从数据库中提取数据 update:更 ...

  7. MySQL数据库1067 问题

    1.MySql1067错误解决方法 http://blog.csdn.net/mhmyqn/article/details/17043921   MySql 1045解决方法 my.ini  mysq ...

  8. LeetCode 387. First Unique Character in a String

    Problem: Given a string, find the first non-repeating character in it and return it's index. If it d ...

  9. Idea 实时编译 和 热部署

    实时编译 idea自动保存编写好的文件,但是不会编译,想要编译需要按ctrl+F9(编译整个项目)ctrl+shift+f9(单个文件),不仅麻烦而且和平常习惯也不相复合.怎么令idea的ctrl+s ...

  10. XVI Open Cup named after E.V. Pankratiev. GP of Ekaterinburg

    A. Avengers, The 留坑. B. Black Widow 将所有数的所有约数插入set,然后求mex. #include<bits/stdc++.h> using names ...