抛出一个格式异常C#

抛出一个格式异常C#,c#,try-catch,formatexception,C#,Try Catch,Formatexception,我试图在有人试图输入非整数字符时抛出一个格式异常,提示输入他们的年龄 Console.WriteLine("Your age:"); age = Int32.Parse(Console.ReadLine()); 我不熟悉C语言,在为这个实例编写try-catch块时需要帮助 Console.WriteLine("Your age:"); age = Int32.Parse(Console.ReadLine()); 非常感谢 无需

我试图在有人试图输入非整数字符时抛出一个格式异常,提示输入他们的年龄

        Console.WriteLine("Your age:");
        age = Int32.Parse(Console.ReadLine());
我不熟悉C语言,在为这个实例编写try-catch块时需要帮助

        Console.WriteLine("Your age:");
        age = Int32.Parse(Console.ReadLine());

非常感谢

无需为该代码设置try-catch块:

        Console.WriteLine("Your age:");
        age = Int32.Parse(Console.ReadLine());
Console.WriteLine("Your age:");
int age;
if (!Integer.TryParse(Console.ReadLine(), out age))
{
    throw new FormatException();
}

该代码将已经抛出
格式异常
。如果你想抓住它,你可以写:

        Console.WriteLine("Your age:");
        age = Int32.Parse(Console.ReadLine());
Console.WriteLine("Your age:");
string line = Console.ReadLine();
try
{
    age = Int32.Parse(line);
}
catch (FormatException)
{
    Console.WriteLine("{0} is not an integer", line);
    // Return? Loop round? Whatever.
}
但是,最好使用
int.TryParse

        Console.WriteLine("Your age:");
        age = Int32.Parse(Console.ReadLine());
Console.WriteLine("Your age:");
string line = Console.ReadLine();
if (!int.TryParse(line, out age))
{
    Console.WriteLine("{0} is not an integer", line);
    // Whatever
}
这避免了用户错误的异常情况。

        Console.WriteLine("Your age:");
        age = Int32.Parse(Console.ReadLine());
Console.WriteLine("Your age:");
try
{    
     age = Int32.Parse(Console.ReadLine());
}
catch(FormatException e)
{
    MessageBox.Show("You have entered non-numeric characters");
   //Console.WriteLine("You have entered non-numeric characters");
}

Int32.Parse
将抛出一个
FormatException
如果向它传递了一个非数字字符串-你的代码看起来像是做了你想做的事情?你的意思是你试图
捕获一个格式异常吗?Int32.Parse可能会返回三个不同的异常这应该会帮助你我对这行有点困惑:如果(!int.TryParse(line,out age)@user1513637:以何种方式?
int.TryParse
返回是否成功,并将结果存储在
out
参数中。有关详细信息,请参阅文档。