为什么表单加载无法捕获异常? [英] Why the form load can't catch exception?

查看:112
本文介绍了为什么表单加载无法捕获异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Winforms中的错误吗? (在VS2008和VS2010上都经过测试)

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

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

我在该代码中未收到任何错误,不久前,我m试图为这个问题制定解决方案从字符串中解析一个非

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

我在Form1_Load中执行以下代码:

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());        
}

我想知道为什么它没有显示数字。然后将代码移到button1_Click ...

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.

为什么Form1_Load没有捕获任何异常,为什么它会静默失败?代码只是从form1_load退出,位于 string t = s.ToCharArray()。TakeWhile ...

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

推荐答案

重写,从那以后我就知道了它的来源。当Windows在64位版本的Windows 7上运行时,如果在32位进程中引发异常,则Windows行为不当。它将吞噬响应于由64位Windows管理器触发的Windows消息而运行的代码所引发的任何异常。 。像WM_SHOWWINDOW一样,导致Load事件引发的消息。

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.

调试器起着一定的作用,因为当调试器处于活动状态时,将关闭Winforms应用程序中的常规异常捕获功能允许调试器在发生异常时停止。在这种情况下不会发生这种情况,因为Windows 7首先吞下了异常,从而阻止了调试器看到它​​。

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.

这篇关于为什么表单加载无法捕获异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆