While developing an UWP application I wanted to log unhandled exceptions. My coach mentioned that in WPF you can register a exception handler to handle unhandled exceptions globally. In UWP it works exactly the same way.

Add Unhandled Exception Handler

NOTE: This solution does not prevent your app from crashing and exiting. This solution only lets you react to unhandled exceptions. Like in my situation you can use this to log those exceptions.

An UnhandledException event contains an argument of type UnhandledExceptionEventArgs. So declare your handling method as follows:

private void OnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
    // Your code to handle the exception

The event will be fired from the current instance of the App class. The following code shows how to register the event handler to the UnhandledException event in the App.xaml.cs during the instantiation:

public App()
    App.Current.UnhandledException += OnUnhandledException;

Now you can, for example, log the exception, which caused your app to crash.

1 Comment »

  1. This is a good solution, but the StackTrace seems to be empty, to be precise it is null everytime an unhandled exception throws. So is there a way to trace the caller method or anything, which causes the exception?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.