WPF global exception handler
You can trap unhandled exceptions at different levels:
AppDomain.CurrentDomain.UnhandledException
From all threads in the AppDomain.Dispatcher.UnhandledException
From a single specific UI dispatcher thread.Application.Current.DispatcherUnhandledException
From the main UI dispatcher thread in your WPF application.TaskScheduler.UnobservedTaskException
from within each AppDomain that uses a task scheduler for asynchronous operations.
You should consider what level you need to trap unhandled exceptions at.
Deciding between #2 and #3 depends upon whether you're using more than one WPF thread. This is quite an exotic situation and if you're unsure whether you are or not, then it's most likely that you're not.
A quick example of code for Application.Dispatcher.UnhandledException:
public App() {
this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
}
void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) {
string errorMessage = string.Format("An unhandled exception occurred: {0}", e.Exception.Message);
MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
// OR whatever you want like logging etc. MessageBox it's just example
// for quick debugging etc.
e.Handled = true;
}
I added this code in App.xaml.cs
You can handle the AppDomain.UnhandledException
event
EDIT: actually, this event is probably more adequate: Application.DispatcherUnhandledException