在 if/switch 块中使用 try-catch 捕获异常

布拉德IM91

我正在尝试在 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 中遇到空引用异常,我想捕获该空引用并显示一条消息。

感谢您的任何帮助/建议!

马修HD

只需将所有必要的代码放入一个单独的函数中,然后检查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;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在 try/catch 块中未捕获异常

@ try @ catch块未捕获异常内部

异常未捕获在try catch块中

try块引发异常,但catch块未捕获异常

使用try / catch不会捕获异常

在Javascript中使用try-catch-finally块来捕获JSON解析异常不起作用

嵌套的try异常是否将被外部catch块捕获

未捕获的异常 PDOException 即使语句在 try/catch 块中

try / catch块捕获异常有什么意义?

在 try/catch 块捕获异常后如何继续执行代码?

C ++ try-catch块未捕获硬件异常

try catch 块仍然返回应该捕获的异常

为什么try catch块没有捕获promise异常?

嵌套的 Try-Catch 块未捕获异常

异常通过try ... catch捕获

c#最佳尝试使用try-catch捕获异常?

Laravel-Vue:如何使用try-catch块在验证请求中捕获验证异常?

Resharper(2016.1 C#)能否建议使用try catch块捕获的异常?

检索/保留文件 - 如果在 Apache Camel 中使用带有 oneexception 的“try..catch”时 catch 块捕获了异常

在 Laravel 中使用 try catch 异常处理

@ try / @ catch没有捕获异常

Try-Catch不会捕获异常

Powershell:在Try / Catch块中使用汇总异常的Handle方法

如何获得try / catch块的IOException异常捕获摆脱的IntelliJ警告/错误的?

如何在for循环中添加try catch块以捕获ArrayIndexOutOfBounds异常?

尽管执行捕获在catch块中,导致try / catch块未能进行异常处理的原因是什么?

PHP try catch块不捕获

try / catch块未捕获libpng错误

try / catch块中未处理的异常