WPF: application does not crash if an exception occurs in the Loaded event

I created a new WPF application and added an event handler for the Loaded event in MainWindow:

Loaded += (s, e) => { throw new Exception("AAAA!"); }; 

Then I run this application from Visual C #, and the application does not crash and does not show an uncaught exception.

I expect it to work, and this application will really crash on other computers. But why does it work on mine?

Update Added screenshot: screenshot

+6
source share
2 answers

The Loaded event can be called from a background thread. When an exception is thrown in this thread, it will be thrown, but will not affect your main application thread. This behavior can be seen in many event handlers, for example. The Timer_Elapsed event handler will also not affect your code as a whole. This does not mean that you should not worry about exceptions inside such code!

+4
source

To catch an exception, you need to either try try / catch in the Loaded method, or you can tell the dispatcher to notify you of an unhandled exception.

Try the following, for example, in the OnStartup method of your application:

 App.Current.DispatcherUnhandledException += (s,e) => { // Handle the exception here var ex = e.Exception; }; 

Edit:

If you want the application to crash, try the following:

 App.Current.DispatcherUnhandledException += (s,e) => { // this should cause your application to crash :-) throw new Exception("Now it should crash!", e.Exception); }; 

The difference is that we create a new exception that is thrown into the user interface.

+6
source

Source: https://habr.com/ru/post/887605/


All Articles