抛出格式异常C#

Ker*_*y G 4 c# try-catch formatexception

我试图在有人试图输入非整数字符的实例中抛出格式异常.

        Console.WriteLine("Your age:");
        age = Int32.Parse(Console.ReadLine());
Run Code Online (Sandbox Code Playgroud)

我不熟悉C#语言,可以使用帮助为此实例编写try catch块.

非常感谢.

Jon*_*eet 20

那段代码已经抛出了FormatException.如果你的意思是想抓住它,你可以写:

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.
}
Run Code Online (Sandbox Code Playgroud)

但是,最好使用int.TryParse:

Console.WriteLine("Your age:");
string line = Console.ReadLine();
if (!int.TryParse(line, out age))
{
    Console.WriteLine("{0} is not an integer", line);
    // Whatever
}
Run Code Online (Sandbox Code Playgroud)

这避免了相当普遍的用户错误情况的例外.