Search code examples
wpfvisual-studio-2010c#-4.0exceptionunhandled-exception

Unhandled Exception Still Crashes Application After Being Caught


I have a WPF application that consists of multiple projects that have forms, classes, base classes, etc..

Because of the large code base I want to make sure if an exception does happen I can catch it, notify the user and let the application continue without crashing. I understand the pros and cons to doing this.

In the App.xaml.cs of the application I have:

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");
}

If an exception happens anywhere those messages boxes are shown which is great, the problem is right after it shows the message the application still crashes. If I run the application in debug, Visual Studio will jump to the place were the exception happened and if I continue it will then go to the message box.

I think the problem has something to do with that but I am not sure. Is there a way to catch the exception like I am above but at the same time not have the application crash after?

Thank You

EDIT The exceptions that get through to the UnhandledException section will be things like NullReference, NotSupported or Database Exceptions for the most park. If a "serious" exception gets cought like Stack Overflow I will simple notify the user and kill the app. I still need to find a way to stop the app from crashing on non serious exceptions though.


Solution

  • I think you need to set

    dispatcherUnhandledExceptionEventArgs.Handled = true;