Catching Exceptions in WPF at the FrameWork Level

前端 未结 2 1442
清酒与你
清酒与你 2021-01-14 16:28

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

2条回答
  •  青春惊慌失措
    2021-01-14 17:01

    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.

提交回复
热议问题