I was reading C# in a nutshell (Threading chapter) and was trying to catch a divide by zero exception that I throw in a new thread from a button event handler. The AppDomain.CurrentDomain.UnhandledException fires as expected. The event handling methods simply show a window called "ErrorWindow". When I step into the constructor of the window, the debugger throw the exception back and the window doesn't show.
Here's what I have:
- Target Framework: 4.5.2
- Target Platform: X64
The application is a WPF windows application and contains two windows:
- MainWindow: Has a button that executes the code snippet below.
- ErrorWindow: Just a blank window to show in the AppDomain.CurrentDomain.UnhandledException event handler
Code snippet:
var thread = new Thread(() =>
{
int result = 100 / int.Parse("0");
});
thread.Start();
I'm attaching the AppDomain.CurrentDomain.UnhandledException event handler in a StartUp event handler in App.xaml.cs. The event handler simply create a instance of the ErrorWindow and attemtps to show it.
If someone is able to recreate this behavior and explain why, that'd be great. I'll share my VS project if needed.
PS: This only happens when I create a thread. If my DivideByZeroException gets thrown from the main UI thread, then the window shows as expected.
PS: Marshalling the showing of the window to the UI thread doesn't work and I don't expect it to. Thanks!
Thread
?Task
makes this scenario much easier, by giving you a supported way to catch and observe the exception – Kevin Gosse