【问题标题】:Catching an Exception with try-catch inside an if/switch block在 if/switch 块中使用 try-catch 捕获异常
【发布时间】:2020-11-13 13:31:07
【问题描述】:

我试图在 switch 语句中的 if 语句中捕获 nullReferenceException...我尝试了多种不同的方法,但我无法真正捕获错误,它只会导致崩溃.

               try 
                {
                switch (selectedOption)
                {

                    case "1":
                        break;
                    case "2":
                        if (textBox1.Text == "TEXT")
                        {
                            MessaageBox.Show("TEXT")
                        }
                        else
                        {
                            MessageBox.Show("ELSETEXT")
                        }
                        throw new Exception;
                    case "3":
                        break;
                     default:
                        break;
                 }
               }
              catch (Exception)
                  {
                     MessageBox.Show("An error has occured");
                  }

如果 textbox1 == text 在案例 2 中出现空引用异常,当没有值时,我想捕获该空引用并显示一条消息。

感谢任何帮助/建议!

【问题讨论】:

  • throw new Exception; 语法无效
  • 我不会使用try..catch 来处理NullReferenceException;它很容易被预防。在您的情况下,无论如何都不会引发异常,因为null == "TEXT" 的计算结果为false,因此没有异常。

标签: c# if-statement switch-statement try-catch


【解决方案1】:

只需将所有必要的代码放入一个单独的函数中,然后检查strings 的值。而不是使用try{} catch{}。如果您只是检查空值,则不建议这样做。

示例函数:

private void CheckText(string text, string equal,
    string error = "Text is empty", string notequal = "ELSETEXT") {
    // Message that we let the user see in the messageBox.
    string messageText = string.Empty;

    // Check if either of the string we want to check for is empty,
    // or null or consists only of whitespaces
    if (string.IsNullOrWhiteSpace(text) || string.IsNullOrWhiteSpace(equal)) {
        messageText = error;
    }
    // Check if both check string are equal
    else if (string.Equals(text, equal)) {
        messageText = equal;
    }
    else {
        messageText = notequal;
    }
    MessageBox.Show(messageText);
}

现在您可以在 catch 块中调用该函数,并将必要的值作为参数提供给函数。

函数调用示例:

case "2":
    CheckText(textBox1.Text, "TEXT");
    break;

【讨论】:

  • 完美,在尝试使用它之前检查值是否为空更有意义谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-06
  • 1970-01-01
  • 2019-07-12
相关资源
最近更新 更多