是什么导致 Winforms 默默地丢弃未处理的异常(没有 try/Catches)?

2023-12-01

我正在向我的 winforms 控件添加新功能,其中一部分要求曾经始终使用的变量现在是可选的(如果它为空,则从第二个源获取数据)。我做了一些更改并运行了我的表单,却发现什么也没有发生,甚至以前有效的功能也没有发生。我很困惑地浏览了代码,发现我的 Winforms 用户控件抛出了一个NullReferenceException当它遇到我的变量时,但在用户界面中没有抛出错误。

我的设置是我有一个UserControl带有组合框。当用户更改该组合框时,它会加载辅助框UserControl在面板中第一个控件有。第二个控制是抛出异常的内容。

以下是代码路径:

    private void cmbActionType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (_loading)
            return;

        // ActionType was changed, update the action.ActionType value
        if (cmbActionType.SelectedItem != null)
        {
            if (cmbActionType.SelectedItem.ToString() == SETVALUE_OPTION)
                _action.ActionType = ActionTypes.SetValue;
            else if (cmbActionType.SelectedItem.ToString() == CHECKVALUE_OPTION)
                _action.ActionType = ActionTypes.CheckValue;
            else
                _action.ActionType = ActionTypes.CustomAction;
        }

        RefreshActionPanel();
        _editor.DataModified();
    } 

    private void RefreshActionPanel()
    {
        // Control defaults
        AnchorStyles styles = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
        UserControl subControl = null;

        // Clear the currently active control
        pnlActionDetails.Controls.Clear();

        // Determine what type of control to load in the panel
        if (cmbActionType.SelectedItem != null && cmbCaseType.SelectedItem != null)
        {
            // SetValue or CheckValue actions
            if (cmbActionType.SelectedItem.ToString() == CHECKVALUE_OPTION || cmbActionType.SelectedItem.ToString() == SETVALUE_OPTION)
            {
                if (_caseTypeMap.ContainsKey(cmbCaseType.SelectedItem.ToString()))
                    subControl = new SetCheckActionControl(_action, _editor, _caseTypeMap[cmbCaseType.SelectedItem.ToString()]);
            }

            // CustomAction action type
            else
            {
                // Check if the requested case is a type or defined in a script
                if (_caseTypeMap.ContainsKey(cmbCaseType.SelectedItem.ToString()))
                {
                    subControl = new CustomActionControl(_action, _editor, _caseTypeMap[cmbCaseType.SelectedItem.ToString()]);
                }

                else if (_editor.ScriptDefinitions.Any(x => x.CaseName == cmbCaseType.SelectedItem.ToString()))
                {
                    var definitions = _editor.ScriptDefinitions.Where(x => x.CaseName == cmbCaseType.SelectedItem.ToString()).ToList();
                    subControl = new CustomActionControl(_action, _editor, definitions);
                }
            }
        }

        if (subControl != null)
        {
            subControl.Anchor = styles;
            subControl.Height = pnlActionDetails.Height;
            subControl.Width = pnlActionDetails.Width;
            pnlActionDetails.Controls.Add(subControl);
        }
    }

    public CustomActionControl(TestAction action, fmEditor editor, IList<TcScriptDefinition> scriptDefinitions) : base(action, editor)
    {
        _loading = true;
        InitializeComponent();

        _scriptDefinitions = scriptDefinitions;

        PopulateActionList();
        SetupDataGrid();

        _loading = false;
    }

    private void SetupDataGrid()
    {
        // Clear the current contents of the datagrid
        grdParameters.Rows.Clear();

        if (cmbAction.SelectedItem == null)
            return;

        // Retrieve the action code from the drop down
        string actionCode = cmbAction.SelectedValue.ToString();

        // Check if any paramters are available for this action
        if (!_availableActionParameters.ContainsKey(actionCode))
            return;

        // Add a new row for each parameter available for this action
        foreach (string param in _availableActionParameters[actionCode])
        {
            string display = param;

            // Determine if the parameter has a display string
            if (_formInstance.CodeDisplayMap.ContainsCode(param))
                display = _formInstance.CodeDisplayMap.GetDisplayStringFromCode(param);

            // Create the array for the row, with an empty string as the current value
            string[] row = { display, string.Empty };

            // Check if the current action uses this action code.  
            //   If so, retrieve the value for this parameter and use it in the row
            //   Note: Case-INsensitive comparison must be performed here
            if (_action.Attributes["action"].Equals(actionCode, StringComparison.CurrentCultureIgnoreCase))
                if (_action.Attributes.ContainsKey(param))
                    row[1] = _action.Attributes[param];

            grdParameters.Rows.Add(row);
        }
    }

The NullReferenceException是来自SetupDataGrid()方法其中_formInstance正在被呼叫。然而,通常当应用程序遇到未处理的异常时,JIT 系统会抛出一条错误消息(如您​​所见,没有try/catch除非我是盲人,否则使用陈述)。

为什么我的 winforms 应用程序没有显示发生异常的迹象。我宁愿出现未处理的异常消息,也不愿什么都没有发生,因为这使得用户更难知道出现了关键问题(而不是不响应他们的命令)


Edit: To clarify since there seems to be some confusion, I do NOT care about breaking on this exception in visual studio when debugging. The fact of the matter is that the application should not be hiding unhandled exceptions, and my application should crash (or rather show the JIT message that an unhandled exception occurred), even when not in debug mode outside of visual studio.

这不是调试时间问题,而是生产运行时间问题。如果这段代码抛出一个OutOfMemoryException例如,我需要它不被默默地忽略。现在它被忽视了。


Go to Debug->Exceptions... (Ctrl-D, E如果您使用的是默认快捷方式),请从 Visual Studio 的菜单栏中选中该框Thrown under Common Language Runtime Exceptions。这将导致您的程序在出现异常时中断,即使它们位于 try/catch 块中。然后,您可以向前迈出一步,查看代码跳转到下一条指令的位置。这应该会将您带到隐藏异常的 catch 块。

它可能会跳到 .NET 代码中进行捕获,您可以转到Debug->Options and Settings..并打开Enable .NET framework Source Stepping看看它正在跳到什么地方。


这是捕获代码中未处理的异常的示例

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
        Application.Run(new Form1());
        MessageBox.Show("0");
    }

    static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
    {
        MessageBox.Show("1");

    }
}
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        throw new ArgumentNullException();
    }
}

单击按钮,出现 1,之后程序仍应运行。

然而,正如我在上一条评论中所说,首先检查“调试”->“异常”中是否选中了“用户未处理”(可能取消选中并重新选中),它可能会解决您的初始问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是什么导致 Winforms 默默地丢弃未处理的异常(没有 try/Catches)? 的相关文章

随机推荐

  • 调试在 Gunicorn 中运行的 Flask 应用程序

    我一直在为我的应用程序使用 nginx gunicorn 和 Flask 开发一个新的开发平台 在操作方面 一切正常 我遇到的问题是调试 Flask 层 当我的代码中出现错误时 我只会直接向浏览器返回 500 错误 并且控制台或日志中不会显
  • 将任何单词替换为其自身的修改版本

    我正在寻找一种简单的方法来转动这个字符串 java javascript vbscript 进入这个字符串 str search java str search javascript str search vbscript 即用以下内容替换
  • 当 Android 4.1.2 (Samsung Galaxy s2 gt-i9100) 的 Manifest.xml 中未指定 android:targetSdkVersion="17" 时,视图(按钮)不可见

    我使用了片段并在每个片段中显示文本动画 在我的 Fragment 活动中 我选择了 下一步 按钮并将其设置为不可见 在片段中完成文本动画后 我使按钮可见并应用 TranslateAnimation 当我在带有 Jelly Bean 的 Sa
  • 使用 php 群发邮件程序还是简单地使用 mail()?

    我正在发送约 30 000 封电子邮件 每条消息的内容都会略有不同 我已经使用 php 阅读过mail 功能对于群发邮件来说不是一个好主意 使用内置的优点和缺点是什么mail 使用群发邮件程序的功能和优缺点 例如斯威夫特梅勒 特别要注意的是
  • 如何从 iPhone 上的用户相册加载图像?

    我想从用户的相册中随机加载图像 但我不想访问图像选择器 即我希望图像是随机背景图像 有谁知道这是否可能 除了 UIImageWriteToSavedPhotosAlbum 之外 我找不到任何参考文献 编辑 我正在尝试在 iPhone 应用程
  • Excel合并多行

    我觉得我错过了一些我想用 Excel 做的简单事情 但我在 Google 上错误地提出了这个问题 就这样 我正在查看一位经营比赛计时公司的朋友的一些 Excel 表格 在一场比赛结束时 他有一张 Excel 表格 其中包含一系列比赛的以下格
  • 将 SVG 过滤器内联为数据 URI

    我尝试使用 CSS 中的数据 URI 添加 SVG 过滤器 但无法将效果应用到我的图像 似乎应该支持它 因为根据 caniuse 所有主要浏览器都支持数据 URI 和 SVG 过滤器 如果我将其保存为 SVG 文件并链接到 css 中的文件
  • 如何在 Android 上的 WebRTC 通话期间将麦克风录制为更压缩的格式?

    我有一个应用程序调用使用WebRTC 但在通话过程中 我需要录制麦克风 WebRTC有一个对象WebRTCAudioRecord录制音频但音频文件太大 PCM 16bit 我想录制但尺寸较小 我试过了MediaRecorder但这不起作用
  • 如何修复 OCaml 中的代码错误?

    我是 OCaml 新手 刚刚找到了在线 OCaml 指南 http try ocamlpro com 到了第五课 我陷入了一些练习中 所以 问题来了 修复所有这些 let 表达式 以便最终获得预期结果 1 let xy let x x an
  • 具有范围的子数组

    我试图将一个对象数组拆分为包含 32 个对象的较小数组 剩下的大约最后放入数组中 这是我正在使用的代码 int a sharedManager inventoryArray2 count float b a 33 int c ceilf b
  • BeginRequest 在 ASP.NET MVC 应用程序中触发静态文件

    我的印象是静态文件 CSS 图像 font face 文件等 完全绕过 ASP NET 并直接由 IIS 提供服务 但是 每个 HTTP 请求都会调用我的 BeginRequest 事件处理程序 包括静态文件的请求 这让我担心 因为我正在创
  • 如何使旧版扩展 (tfs 2013) 在 tfs 2015 update 2 中工作?

    我们让这个扩展在 tfs 2013 下工作 它只是隐藏了积压项目的快速添加面板 请参见下面的代码 我们将服务器更新到 tfs 2015 2 后 代码停止工作 无法使用 VSTS 扩展的新框架 请参阅上一个问题 这是 JavaScript 代
  • 使用包含浮点数组的 OpenCL 将结构传递到 GPU

    我目前有一些数据想要传递到我的 GPU 并将其乘以 2 我创建了一个结构 可以在这里看到 struct GPUPatternData cl int nInput nOutput patternCount offest cl float pa
  • 当类包含在另一个类中时,为什么不转发类工作的声明

    这编译 include Sprite h class GameObject public int x y w h Sprite sprite public GameObject GameObject int x int y int w in
  • 我可以使用 VC++ 2008 创建 Dll 并在 VC++ 6 中使用它吗?

    我用 VC 2008 制作了一个 DLL 当我在控制台应用程序 VC 6 0 中使用它时 出现异常 msvcr90 dll 0xc0000005 访问冲突 Access Violation在这种情况下可以意味着很多事情 并且msvcr90
  • 后台服务之间如何通信

    我正在实现一个应用程序 因为我有两个服务 一个服务执行某些任务并将某些值传递给另一个服务 然后该服务使用该值执行某些任务 当第一个服务生成第一个值时 它应该启动第二个服务 此后 第一个服务生成的值将添加到第二个服务的队列中 第一次当第二个服
  • 从 C# 调用 VBA 函数

    是否可以调用一个 VBA 函数 在 Access 中 该函数从外部世界获取两个字符串参数 例如从 c 中 但其他函数也可以这样做 这是从 C 调用 Access 数据库函数的示例 我过去曾使用该函数来创建类似的功能 private void
  • HTTP 保持活动状态和 ServiceHost / C#?

    如何使用应用程序配置和 C ServiceHost 启用 禁用 HTTP Keep alive 并设置自托管服务的连接超时 例如 MyService service new MyService ServiceHost serviceHost
  • 未定义的变量:GPVAL_DATA_Y_MIN(Gnuplot)

    基于这篇文章 我正在使用 gnuplot gnuplot 4 6 patchlevel 1 gnuplot 范围内的最大值和最小值 我正在尝试使用set yr GPVAL DATA Y MIN GPVAL DATA Y MAX 在我的 pg
  • 是什么导致 Winforms 默默地丢弃未处理的异常(没有 try/Catches)?

    我正在向我的 winforms 控件添加新功能 其中一部分要求曾经始终使用的变量现在是可选的 如果它为空 则从第二个源获取数据 我做了一些更改并运行了我的表单 却发现什么也没有发生 甚至以前有效的功能也没有发生 我很困惑地浏览了代码 发现我