3

我有一个WPF应用程序,包含有窗体,类,基础类等多个项目的..未处理的异常仍然崩溃的应用被抓后

由于大量的代码库我想如果一个确保的异常会发生,我可以捕捉它,通知用户,让应用程序继续而不会崩溃。我明白这样做的优点和缺点。

在应用程序中的App.xaml.cs我:

private void OnApplicationStartup(object sender, StartupEventArgs e) 
{ 
    Application.Current.DispatcherUnhandledException += CurrentOnDispatcherUnhandledException; 
    AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException; 
    Dispatcher.UnhandledException += DispatcherOnUnhandledException; 
    UI.Views.Windows.MainWindow.Show(); 
} 

private void DispatcherOnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs dispatcherUnhandledExceptionEventArgs) 
{ 
    MessageBox.Show("TEST 3"); 
} 

private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs) 
{ 
    MessageBox.Show("TEST 2"); 
} 

private void CurrentOnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs dispatcherUnhandledExceptionEventArgs) 
{ 
    MessageBox.Show("TEST 1"); 
} 

如果有异常情况发生的任何地方那些箱子中显示,这是伟大的消息,问题是它显示的信息,应用程序仍然之后崩溃。如果我在调试中运行应用程序,Visual Studio将跳转到发生异常的地方,如果我继续,它将转到消息框。

我认为问题与此有关,但我不确定。有没有办法像上面那样捕捉异常,但同时又没有应用程序崩溃?

谢谢

编辑 通过对UnhandledException节得到的将是一些类似NullReference,notsupported时或在大多数公园数据库异常的异常。如果一个“严重”的异常像堆栈溢出一样,我会简单地通知用户并杀死应用程序。尽管如此,我仍然需要找到一种方法来阻止应用程序在非严重异常上崩溃。

回答

10

我认为你需要设置

dispatcherUnhandledExceptionEventArgs.Handled = true; 

dispatcherUnhandledExceptionEventArgs.Handled = true; 
+0

太简单了....哇。非常感谢! – 2012-08-19 06:21:44

+0

很高兴帮助:) – ivowiblo 2012-08-19 08:02:41

+9

unhandledExceptionEventArgs没有处理属性:( – Firo 2013-08-13 11:04:12

0

你的应用程序捕获什么样的异常?除非您正在设置HandleProcessCorruptedStateExceptionsAttribute属性,否则对于更改状态的异常使用UnhandledException将不起作用。

From MSDN documentation: 
AppDomain.UnhandledException Event 

从.NET Framework 4开始,则不会引发例外这一事件的过程中损坏的状态,如堆栈溢出或访问冲突,除非该事件处理程序是安全关键和具有HandleProcessCorruptedStateExceptionsAttribute属性。

http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx

+0

通过对UnhandledException节得到的将是一些类似NullReference,notsupported时或数据库异常的异常。如果一个“严重”的异常像堆栈溢出一样,我会简单地通知用户并杀死应用程序。所以我需要找到一种方法来阻止应用程序在非严重例外情况下崩溃。 – 2012-08-19 06:01:22