c# - 有没有办法在 catch block 中编写 if 语句?

标签 c# winforms

我想要的是,如果没有引发异常,按钮 6 和 8 对用户可见。无论异常如何,finally block 都会运行,所以我不会把它放在那里

        if (worksheet == null)
            return;
        try
        {
            Range allo = worksheet.Rows.Cells[72, 2];
            allo.Value = AcceptableNoise.SelectedItem.ToString();
        }
        catch (Exception ee)
        {
            if (ee.Data != null)
            {
                _ = MessageBox.Show("One or more Options not selected " +
               "\n Eg: Confirm that Actuator Type is selected"/*ee.ToString()*/, "Selection Error", 
                MessageBoxButtons.OK, MessageBoxIcon.Hand);

            }
            else
            {
                button8.Visible = true;
                button6.Visible = true;
            }

        }
        
        
        finally
        {

            excel2.DisplayAlerts = false;
            excel2.ActiveWorkbook.Save();
            excel2.Application.Quit();
            excel2.Quit();


            /// = MessageBox.Show("You are done");
        }

最佳答案

这里是一些应该可以工作的代码示例。如果一切正确,将会出现按钮。除非他们会隐藏或保持隐藏状态。

try
{
    Range allo = worksheet.Rows.Cells[72, 2];
    allo.Value = AcceptableNoise.SelectedItem.ToString();
    button8.Visible = true;
    button6.Visible = true;
}
catch (Exception ee)
{
    MessageBox.Show("One or more Options not selected " +
        "\n Eg: Confirm that Actuator Type is selected"/*ee.ToString()*/, 
        "Selection Error", 
        MessageBoxButtons.OK, MessageBoxIcon.Hand);

    button8.Visible = false;
    button6.Visible = false;
}               
finally
{
    excel2.DisplayAlerts = false;
    excel2.ActiveWorkbook.Save();
    excel2.Application.Quit();
    excel2.Quit();

    MessageBox.Show("You are done");
}

但有一个条件非常重要 - button8.Visible = true 之前的代码必须在需要时抛出异常。如果没有,按钮无论如何都会出现。

关于c# - 有没有办法在 catch block 中编写 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64955432/

相关文章:

c# - 如何在 Windows 窗体应用程序中创建 Alt 快捷方式?

c# - 如何触发当前类(class)无法触及的事件?

c# - 使用 WebClient 时应用程序在启动时卡住

c# - 如何在使用 C# 执行 SQL 查询之前验证它

c# - 混合 C# 和 VB.NET 项目 = 损坏 "Go to definition"

c# - Devart.Data.MySql.MySqlDependency 不适用于多个连接

c# - 是否可以在调整频率的同时在 C# 中生成恒定的声音?

c# - 生成资源任务失败错误

c# - 锁定属性

c# - 有没有办法让 RazorEngine 抛出异常来呈现使用 JSON 作为数据模型的模板?