#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>
Advertisements