抛出一个格式异常C# [英] Throw a format exception C#
本文介绍了抛出一个格式异常C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想扔在例如某人格式异常试图促使他们的年龄时,进入一个非整数的性格。
I'm trying to throw a format exception in the instance someone tries to enter a non-integer character when prompted for their age.
Console.WriteLine("Your age:");
age = Int32.Parse(Console.ReadLine());
我不熟悉C#语言,可以写一个try catch块这个实例中使用帮助。
I'm unfamiliar with C# language and could use help in writing a try catch block for this instance.
非常感谢。
推荐答案
这代码已经抛出 FormatException
。如果你的意思是你想要的抓的话,你可以写:
That code will already throw an FormatException
. If you mean you want to catch it, you could write:
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:");
string line = Console.ReadLine();
if (!int.TryParse(line, out age))
{
Console.WriteLine("{0} is not an integer", line);
// Whatever
}
这避免了异常的相当平常情况下,的用户错误。
This avoids an exception for the fairly unexceptional case of user error.
这篇关于抛出一个格式异常C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文