Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

exception

wpf

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

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

Then i start this application from Visual C# and the application doesn't crash nor show an uncaught exception.

I expect that it would crash and this application indeed crashes on other computers. But why does it work on mine?

Update Added a screenshot:screenshot

like image 766
meze Avatar asked May 09 '11 10:05

meze


2 Answers

To catch the exception you need to either do a try/catch in the Loaded method, or you can tell the Dispatcher to notify you when an unhandled exception occurs.

Try the following, for instance 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 then 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 here is that we create a new exception that is thrown on the UI-thread.

like image 175
Rune Grimstad Avatar answered Nov 04 '22 02:11

Rune Grimstad


The Loaded event is propably called from a background thread. When an exception is thrown in this thread, it will be terminated, but will not affect your main application thread. This behaviour can be seen in many event handlers, e.g. a Timer_Elapsed event handler will also not affect your code generally. This dows not mean you shouldn't care about the exceptions inside such code!

like image 34
eFloh Avatar answered Nov 04 '22 01:11

eFloh