Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

winforms - Why the form load can't catch exception?

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 Parse a number from a string with non-digits in between

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...

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Rewrite, I've since figured out where it comes from. Windows misbehaves when an exception is raised in a 32-bit process when it runs on a 64-bit version of Windows 7. It swallows any exception raised by code that runs in response to a Windows message that's triggered by the 64-bit windows manager. Like WM_SHOWWINDOW, the message that causes the Load event to get raised.

The debugger plays a role because when it is active, normal exception trapping in a Winforms app is turned off to allow the debugger to stop on an exception. That doesn't happen in this scenario because Windows 7 swallows the exception first, preventing the debugger from seeing it.

I've written about this problem more extensively in this answer, along with possible workarounds.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...