Oftentimes for troubleshooting purposes it is necessary to trap and report unhandled exceptions. This article will demonstrate how to accomplish this within a WPF application.
The default behavior of a WPF application is to catch all unhandled exceptions, alert the user that the software has encountered a fatal error (shown below), and then shut the application down.
Note that in a fully featured production system, rather than display a custom error screen (or log exceptions to a data file) it is possible/desirable to use Windows Error Reporting to analyze errors within your application. When the user presses the “Send Error Report” button Microsoft captures the error report, which you can then view (using a secure account) to identify problem areas.
To display an error report directly within your WPF application, you can trap all unhandled exceptions using the Application.DispatcherUnhandledException event. This is done by modifying the App.xaml and App.xaml.cs files.
In App.xaml, the registration of the event handler is initialized (highlighted below).
A method is added to App.xaml.cs which will handle this event. This is where the exception handling logic will be added.
DispatcherUnhandledException will only handle exceptions thrown on the UI thread. In multithreading applications, you must ensure that exceptions thrown on secondary threads are caught and re-thrown (or handled) on the UI thread. Unfortunately, there is no built-in mechanism for this behavior.
The sample application (source here) displays a window containing a button which fires an exception. The DispatcherUnhandledException event handler is used to display an “Exception Viewer” window, which displays the details of the exception.
As a best practice, you typically do not want to show the end-user the technical details of an exception. A more robust system of error reporting could be implemented that would securely report exception details, while the end-user would only see a dialog that an error has been encountered.
Another alternative is that you could use Windows Error Reporting for deployed solutions, which could be disabled in favor of custom error reporting for internal or development (beta) systems.