views:

27

answers:

2

Is this a bug in Winforms? (tested on both VS2008 and VS2010)

private void Form1_Load(object sender, EventArgs e)
{
    throw new Exception("Hey");            
}

I don't receive any error in that code, awhile ago, I'm trying to formulate a solution for this question http://stackoverflow.com/questions/3204673/parse-number-from-string-value-in-c

And I do this code in Form1_Load:

private void Form1_Load(object sender, EventArgs e)
{
    MessageBox.Show("X");
    string s = "12ACD";
    string t = s.ToCharArray().TakeWhile(c => char.IsDigit(c)).ToArray().ToString();
    MessageBox.Show("Y");
    int n = int.Parse(t);
    MessageBox.Show(n.ToString());        
}

I wonder why it didn't show the number. Then on moving the code to button1_Click...

private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show("X");
    string s = "12ACD";
    string t = s.ToCharArray().TakeWhile(c => char.IsDigit(c)).ToArray().ToString();
    MessageBox.Show("Y");
    int n = int.Parse(t);
    MessageBox.Show(n.ToString());        
}

...then I noticed that there's an error: Input string was not in a correct format.

Why Form1_Load didn't catch any exception, why it silently fail? The code just exit out of form1_load at string t = s.ToCharArray().TakeWhile...

A: 

The WinForms framework classes won't automatically catch any exceptions for you. That isn't a bug, it's by design - what would they do with the exception?

You have to have your own try/catch block in any event or alternatively handle the Application.ThreadException event. That event can be helpful for some generic handling code like logging the exception or displaying an error dialog, but obviously it can't do anything specific to any individual event or exception type.

Evgeny
try to execute my code above. contrast the behavior of **throw new Exception("Hey Yo!")** in Form1_Load and when it is in button1_Click
Hao
+1  A: 

Yes it is a bug. I haven't as yet figured out exactly where it comes from but it appears to have something to do with the 64-bit debugger. To work around it, use Project + Properties, Build tab, Platform target = x86. You can leave that setting for the Release configuration at Any CPU.

It's the default setting in VS2010, many things work much better in 32-bit mode. Especially Edit + Continue.

Hans Passant
seems a bug. while inside VS it fail silently, it doesn't catch any exception. if run independently, it's able to catch the exception
Hao