我正在尝试在 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 中遇到空引用异常,我想捕获该空引用并显示一条消息。
感谢您的任何帮助/建议!
只需将所有必要的代码放入一个单独的函数中,然后检查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] 删除。
我来说两句