c# Windows Forms Application Exception not thrown!
I have a strange problem, will appreciate if anyone can help.
I have the following function:
v开发者_开发问答oid Foo()
{
MessageBox.Show("here");
throw new Exception();
}
I call it in the following two cases (separately - not at the same time):
private void Form2_Load(object sender, EventArgs e)
{
// Case 1
Foo();
}
public Form2()
{
InitializeComponent();
// Case 2
Foo();
}
I can see the messagebox (I receive message "here") in both case but:
[Case 1] The application doesn't break on the exception (in Debug mode) and remains silent!
[Case 2] Application correctly breaks and I can see that there is an exception in the Foo().
Any idea why?
My guess is that the call to the constructor looks a bit like this:
Form2 form = new Form2();
Application.Run(form);
The crucial part being that you are calling the constuctor of Form2
directly wheras it is the application class / message pump that is calling Form2_Load
.
The final piece of the puzzle is that exceptions thrown inside a Win32 message pump are handled differently (to start with see the Application.SetUnhandledExceptionMode Method ) - what you may also find confusing is that exceptions are also handled differently based on whether the project is build in the Debug configuration or not.
You might have a handler for the Application.UnhandledException Event - this would explain the behaviour you have described.
Application.ThreadException +=
(o, args) =>
{
// Case 1
MessageBox.Show(args.Exception.ToString());
};
try
{
Application.Run(new Form1());
}
catch (Exception ex)
{
// Case 2
MessageBox.Show(ex.ToString());
}
精彩评论