尝试捕获不显示formatException

时间:2019-02-25 03:16:46

标签: c# exception-handling

我正在尝试从文本框中捕获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");
}

4 个答案:

答案 0 :(得分:0)

尝试此以显示消息。

    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");
        }

答案 1 :(得分:0)

您可以像这样在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");
            }
        }

答案 2 :(得分:-1)

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

将ex用作Catch中的变量。

更新(根据评论)

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

答案 3 :(得分:-1)

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

import numpy as np
import matplotlib.pyplot as plt

x = [0.001]
a = np.linspace(0.2,1,100000)
for i in range(1,a.shape[0]):
    x.append(a[i]*np.sin(np.pi*x[i-1]))

fig = plt.figure(figsize=(8,4))
plt.scatter(a,x,s=0.1)

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

更新

您真正应该做的是:

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");
    }