未处理的异常在被捕后仍然会崩溃应用程序

Lan*_*ens 3 wpf exception-handling visual-studio-2010 unhandled-exception c#-4.0

我有一个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");
}
Run Code Online (Sandbox Code Playgroud)

如果在任何地方发生异常,那么显示的消息框很棒,问题就在它显示应用程序仍然崩溃的消息之后.如果我在调试中运行应用程序,Visual Studio将跳转到发生异常的地方,如果我继续它将转到消息框.

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

谢谢

编辑 进入UnhandledException部分的异常将是大多数公园的NullReference,NotSupported或Database Exceptions.如果像"Stack Overflow"这样的"严重"异常,我会简单地通知用户并杀死应用程序.我仍然需要找到一种方法来阻止应用程序崩溃非严重异常.

Ivo*_*Ivo 11

我想你需要设置

dispatcherUnhandledExceptionEventArgs.Handled = true;
Run Code Online (Sandbox Code Playgroud)

  • unhandledExceptionEventArgs没有Handled属性:( (9认同)
  • @Firo,[布莱恩库克关于未处理例外的文章](http://www.bryancook.net/2013/07/unhandled-exceptions-in-wpf-applications.html)可以解释原因."如果你的代码到达这个事件处理程序,它是完全不可恢复的......阻止对话的唯一方法是使用Environment.Exit(1);" (3认同)