简体   繁体   English

抛出格式异常C#

[英]Throw a format exception 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());

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. 非常感谢。

That code will already throw an FormatException . 该代码已经抛出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.
}

However, it would be better to 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. 这避免了相当普遍的用户错误情况的异常。

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");
}

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM