Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Thanks very much.

like image 743
Kerry G Avatar asked Sep 23 '12 06:09

Kerry G


2 Answers

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.

like image 163
Jon Skeet Avatar answered Sep 30 '22 17:09

Jon Skeet


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");
}
like image 39
Ravindra Bagale Avatar answered Sep 30 '22 15:09

Ravindra Bagale