#49 – 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.  This will result in a window similar to the following:

When this happens, the application exits suddenly, the user has no chance to save any uncompleted work and the user gets no additional information.  In short, the application crashes.

You can handle exceptions that would otherwise be unhandled by handling the Application.DispatcherUnhandledException event.  In the example below, we display a better error message and set the Handled property, to avoid shutting down the 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;

This results in a better error:


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #49 – Unhandled Exceptions

  1. Pingback: #1,101 – Defining a Handler for Unhandled Exceptions | 2,000 Things You Should Know About WPF

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: