#1,101 – Defining a Handler for Unhandled Exceptions

When an exception gets thrown in a WPF application and not handled anywhere in the code, an unhandled exception occurs and the application is forced to exit.

You can handle exceptions that would otherwise be unhandled by handling theApplication.DispatcherUnhandledException event.  Below, we display a better error message and set the Handled property, to avoid shutting down the application.

This handler should be defined in the main application class (inherits from Application).

private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
    string friendlyMsg = string.Format("SO sorry that something went wrong.  The error was: [{0}]", e.Exception.Message);
    string caption = "Error";
    MessageBox.Show(friendlyMsg, caption, MessageBoxButton.OK, MessageBoxImage.Error);

    // Signal that we handled things--prevents Application from exiting
    e.Handled = true;
}

We wire up the handler by setting a value for DispatcherUnhandledException in XAML.

<Application x:Class="WpfApplication1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml"
             DispatcherUnhandledException="Application_DispatcherUnhandledException">
</Application>

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #1,101 – Defining a Handler for Unhandled Exceptions

  1. Pingback: Dew Drop – June 25, 2014 (#1803) | Morning Dew

  2. Pingback: Dew Drop – June 26, 2014 (#1804) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: