这是我的代码。当用户点击"计算"按钮,代码将执行它。但是,如果用户没有输入任何数字,则会抛出异常并弹出错误消息。我不知道我的错误信息是"你忘记了这个号码!"但是自动消息显示"输入字符串的格式不正确"弹出。如何更改错误消息?
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
// Local variables
String num1;
String num2;
double number1;
double number2;
double result;
// Get the numbers from the textboxes
num1 = txtInput1.Text;
num2 = txtInput2.Text;
number1 = double.Parse(num1);
number2 = double.Parse(num2);
// Determine the user clicks the Addition radiobutton
if (rdbAdd.Checked)
{
// Add two numbers
result = number1 + number2;
}
else
{
// Determine the user clicks the Subtraction radiobutton
if (rdbSubtract.Checked)
{
// Subtract numbers
result = number1 - number2;
}
else
{
// Determine the user clicks the Multiply radiobutton
if (rdbMultiply.Checked)
{
// Multiply numbers
result = number1 * number2;
}
else
{
// Devide numbers when the user clicks the Devision radiobutton
result = number1 / number2;
}
}
}
// Display the result
txtDisplay.Text = result.ToString();
}
catch (Exception ex)
{
// Display an error message
MessageBox.Show(ex.Message);
}
}
答案 0 :(得分:1)
显示您选择的消息......
MessageBox.Show("Your message goes here.")
例外有它自己的消息,你应该拦截你感兴趣的异常类型,并将你的消息显示为异常。如果文本字段中没有任何内容,则Double.Parse
会抛出异常(请查看Double.Parse
以查看它引发的异常)
但如果number2为零,并且用户选择"除",则会得到一个不同的异常(除以零)。
通常,您应验证输入,只需使用Double.Parse
即可。但通常情况下,您需要更多。此外,如果您打算将应用程序国际化,则需要根据区域设置进行解析。请参阅上面的链接,有一种用于本地化解析的方法。
答案 1 :(得分:1)
这是此例外的默认消息,即FormatException
。
您可以捕获这种异常,然后只显示您自己的消息:
try
{
.... your code ...
}
catch (FormatException ex)
{
//FormatException was thrown, display your message
MessageBox.Show("You forgot to put the number!");
}
catch (Exception ex)
{
// Some other kind of exception was thrown ...
MessageBox.Show(ex.Message);
}
答案 2 :(得分:1)
您可以拥有多个“catch”子句,每个子句对应您要处理的每种类型的异常:
try
{
// Your code goes here
}
catch (DivideByZeroException ex)
{
MessageBox.Show("Cannot divide by zero! " + ex.Message);
}
catch (Exception ex)
{
// This is a generic exception
MessageBox.Show("Error: " + ex.Message);
}
您必须从更具体到更通用的顺序进行排序。
答案 3 :(得分:1)
可能是你试试这个,如果其中一个txtInput1和txtInput2为null或为空,则无法继续。
if(string.IsNullOrWhiteSpace(txtInput1.Text) == true)
{
MessageBox.Show("Your message goes here.");
return; // this is important, return if true
}
if(string.IsNullOrWhiteSpace(txtInput2.Text) == true)
{
MessageBox.Show("Your message goes here.");
return; // this is important, return if true
}
// then
. . . . . // proceed if no problem found