开发者

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

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:开发者_如何学Go

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


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜