1
votes

WPF provides a very convenient way to handle unexpected exceptions: I can just attach a handler to the Application.DispatcherUnhandledException event and all unhandled exceptions go this way:

Application.Current.DispatcherUnhandledException += (sender, e) => {
    // Show message, log exception, etc.
};

This works great for WPF application projects. Now, I have a library with WPF windows, which is called from a non-WPF application (it's a legacy VBA app, and the WPF library is made accessible via COM interop).

So, the thing is: I can create, open and show WPF windows (this works fine), but I don't have an Application instance. Application.Current is null. I use the WPF classes, but I operate them outside the WPF application framework.

Currently, the only drawback of this solution is that exceptions in WPF window event handler code are silently swallowed:

void Button_click(sender as object, e as RoutedEventArgs) {
    ...
    // some exception occurs here, but nobody hears her scream
    ...
}

I don't like that. I'd like to log them and show error messages.

My question: Is there a way to globally catch unhandled exceptions in this scenario or do I have to add a gerneric try-catch-log block to every WPF window event handler code I write?

What I have tried:

  • Attaching to AppDomain.CurrentDomain.UnhandledException. Doesn't work. Exceptions don't get there.
  • Reading the relevant parts of MSDN regarding WPF and Win32 interop (Ref 1, Ref 2, Ref 3). Exceptions are not mentioned there.
1

1 Answers

2
votes

Attach to the Dispatcher instead:

Dispatcher.CurrentDispatcher.DispatcherUnhandledException += (sender, e) => { 
    // Show message, log exception, etc. 
}; 

If no dispatcher exists yet, accessing CurrentDispatcher automatically creates a singleton Dispatcher which will also be used by the WPF windows.