Throw a format exception C#

馋奶兔 提交于 2019-12-09 03:38:14

问题


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.

Thanks very much.


回答1:


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.
}

However, it would be 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
}

This avoids an exception for the fairly unexceptional case of user error.




回答2:


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



回答3:


No need to have a try catch block for that code:

Console.WriteLine("Your age:");
int age;
if (!Integer.TryParse(Console.ReadLine(), out age))
{
    throw new FormatException();
}


来源:https://stackoverflow.com/questions/12550184/throw-a-format-exception-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!