I\'m developing a light-weight WPF MVVM framework, and would like to be able to catch unhandled exceptions, and ideally recover from them.
Ignoring for the moment al
A quick answer to my own question:
This works...
App.xaml.cs:
protected override void OnStartup(StartupEventArgs e)
{
Application.Current.DispatcherUnhandledException +=
new DispatcherUnhandledExceptionEventHandler(DispatcherUnhandledExceptionHandler);
base.OnStartup(e);
}
void DispatcherUnhandledExceptionHandler(object sender, DispatcherUnhandledExceptionEventArgs args)
{
args.Handled = true;
// implement recovery
// execution will now continue...
}
[Edit: My comments below have nothing to with the implementation, but my specific IDE (Visual Studio) config with respect to exception catching by the IDE. Please see Isak's comments above.]
BUT, and it's a big but, if you're executing from within VisualStudio, then YOU WILL STILL GET THE VS exception notification dialog box popping up, and the DispatcherUnhandledExceptionHandler will only be invoked if you press F5/continue, after which execution will continue as per normal.
If you're running the compiled binary directly, i.e from the command line or via Windows Explorer, then the handler will be invoked as you would expect, without any intermediary popup.
The reason VS shows you the exception is because you have set it up like that (either you did this explicitly or - more likely - the defaults in VS configured it like this). You can control what Visual Studio does when it encounters an exception in the debugged code through the Debug->Exceptions
menu.
You can even make it break even though you have a catch for it which is quite handy in some cases.
If you're not using multi threading then you should be fine with the DispatcherUnhandledException event since it will catch everything that gets uncaught on the main UI thread.