WPF global exception handler [duplicate] WPF global exception handler [duplicate] wpf wpf

WPF global exception handler [duplicate]


You can trap unhandled exceptions at different levels:

  1. AppDomain.CurrentDomain.UnhandledException From all threads in the AppDomain.
  2. Dispatcher.UnhandledException From a single specific UI dispatcher thread.
  3. Application.Current.DispatcherUnhandledException From the main UI dispatcher thread in your WPF application.
  4. 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.


You can handle the AppDomain.UnhandledException event

EDIT: actually, this event is probably more adequate: Application.DispatcherUnhandledException


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