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:
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With