7.13. Dealing with Unhandled Exceptions in Windows Presentation Foundation (WPF) Applications

Problem

You have a Windows Presentation Foundation-based (WPF) application in which you want to catch and log any unhandled exceptions on any thread.

Solution

To hook up the necessary event handlers to catch all of your unhandled exceptions in a WPF application, add the following code to the App.xaml file in your application:

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

	   </Application.Resources>
	</Application>

Then, in the code behind file App.xaml.cs, add the Application_ DispatcherUnhandledException method to handle otherwise unhandled exceptions:

	private void Application_DispatcherUnhandledException(object sender,
	          System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
	{
	    // Log the exception information in the event log
	    EventLog.WriteEntry("UnhandledWPFException Application",
	        e.Exception.ToString( ), EventLogEntryType.Error);
	    // Let the user know what happenned
	    MessageBox.Show("Application_DispatcherUnhandledException: " + e.Exception.
	ToString( ));
	    // indicate we handled it
	    e.Handled = true;
	    // shut down the application
	    this.Shutdown( );
	}

Discussion

Windows Presentation Foundation ...

Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.