我试图在有人在提示输入年龄时尝试输入非整数字符的实例中抛出格式异常。
Console.WriteLine("Your age:");
age = Int32.Parse(Console.ReadLine());
我不熟悉 C# 语言,可以使用帮助来为此实例编写 try catch 块。
非常感谢。
该代码已经抛出一个FormatException
。如果你的意思是你想要catch它,你可以写:
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.
}
然而,这将是better to use 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
}
这避免了相当平常的用户错误情况的异常。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)