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: