uhlenheuerdotnet
programming, .NET, linux and others

WPF: How to catch unhandled exceptions

by Gregor Uhlenheuer on October 6, 2011

In order to catch unhandled exceptions in WPF applications you are not able to hook into the event you are used to from WinForms - now there are even three levels you can listen for unhandled exceptions on.

UnhandledException

The first event you can attach to is the UnhandledException event of the current application domain. See the documentation on the msdn for more information.

AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException +=
    new UnhandledExceptionEventHandler(CustomHandler);

// ...

private static void CustomHandler(object sender, UnhandledExceptionEventArgs e)
{
    Exception ex = (Exception) e.ExceptionObject;
    Console.WriteLine("Caught unhandled exception: " + ex.Message);
}

DispatcherUnhandledException

The event DispatcherUnhandledException is triggered by the main UI dispatcher of your WPF application. The documentation can be found on the msdn.

Application.Current.DispatcherUnhandledException +=
    new DispatcherUnhandledExceptionEventHandler(CustomHandler);

// ...

private static void CustomHandler(object sender, DispatcherUnhandledExceptionEventArgs e)
{
    Console.WriteLine("Caught unhandled exception: " + e.Exception.Message);
}

Moreover it is possible to hook into the DispatcherUnhandledException event of a specific Dispatcher instance. The behavior is described in the documentation on the msdn in more detail.

dispatcher.DispatcherUnhandledException +=
    new DispatcherUnhandledExceptionEventHandler(CustomHandler);

References

This post is tagged with c#, .net and wpf