#49 – Unhandled Exceptions
August 30, 2010 1 Comment
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: