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() { InitializeComponent(); App.Current.UnhandledException += OnUnhandledException; }
Now you can, for example, log the exception, which caused your app to crash.
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?