繁体   English   中英

尝试捕获不显示formatException的错误消息

[英]Try catch not showing error message for formatException

我正在尝试从文本框中捕获FormatException 例如-如果用户在名称文本框字段内输入数字或其他任何字符。 消息将会弹出-出现问题。 我对C#相当陌生,我不理解异常的概念。 下面不起作用。 什么是无效格式的正确例外?

private void button1_Click(object sender, EventArgs e)
{
try
{
    string name = textBox1.Text;
    int age = int.Parse(textBox2.Text);

}
catch (FormatException )
{
    MessageBox.Show("Something went wrong");
}

尝试显示消息。

    try
        {
            double mydoubleParam = 0;
            // Assuming textBox1.Text is Name test box
            if (double.TryParse(textBox1.Text, out mydoubleParam))
            {
                 new Exception(" Numeric value in name field");
            }

            int age = int.Parse(textBox2.Text);// Assuming Number text box

            MessageBox.Show("How are you today?");
        }

        catch (FormatException ex)
        {
            MessageBox.Show("Something went wrong");
        }

您可以像这样在TextChanged事件中处理它:

private void textBox1_TextChanged(object sender, EventArgs e)
        {
            int a;
            bool isNumeric = int.TryParse(textBox1.Text, out a);
            if (isNumeric)
            {
                MessageBox.Show("Something went wrong");
            }
        }
 catch (FormatException  ex)
    {
       MessageBox.Show("Something went wrong " + ex.ToString() );
    }

将ex用作Catch中的变量。

更新(根据评论)

 catch (FormatException  ex)
{
   MessageBox.Show("Something went wrong !");
}

如果需要在名称文本框中检查数字,则:

try {
        string name = textBox1.Text;
        Regex regex = new Regex("[0-9]");
        if (regex.IsMatch(name)) {
            throws new FormatException();
        }
        int age = int.Parse(textBox2.Text);
        MessageBox.Show("How are you today?");
    }
    catch (FormatException) {
       MessageBox.Show("Something went wrong");
    }

对于每种情况,您还应该显示更具体的消息。

更新

您真正应该做的是:

var regex = new Regex("[0-9]");
if (regex.IsMatch(textBox1.Text)) {
    MessageBox.Show("There was a number inside name textbox.","Error in name field!");
    return;
}
try {
    Convert.ToInt32(textBox2.Text);
} catch (Exception) {
    MessageBox.Show("The input in age field was not valid","Error in name field!");
    return;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM