抛出格式异常 C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12550184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Throw a format exception C#
提问by Kerry G
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());
I'm unfamiliar with C# language and could use help in writing a try catch block for this instance.
我不熟悉 C# 语言,可以使用帮助为此实例编写 try catch 块。
Thanks very much.
非常感谢。
采纳答案by Jon Skeet
That code will already throw an FormatException. If you mean you want to catchit, you could write:
该代码已经将抛出一个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.
}
However, it would be betterto use int.TryParse:
但是,最好使用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.
这避免了相当普通的用户错误情况的异常。
回答by Prescott
No need to have a try catch block for that code:
无需为该代码设置 try catch 块:
Console.WriteLine("Your age:");
int age;
if (!Integer.TryParse(Console.ReadLine(), out age))
{
throw new FormatException();
}
回答by Ravindra Bagale
What about this:
那这个呢:
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");
}

