Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Windows Forms Application Exception not thrown!

I have a strange problem, will appreciate if anyone can help.

I have the following function:

void 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?

like image 337
Mo Valipour Avatar asked Jun 30 '11 15:06

Mo Valipour


1 Answers

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.

like image 173
Justin Avatar answered Oct 25 '22 11:10

Justin