Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to re-ask for input in try catch statement

Tags:

c#

string l = Console.ReadLine();

try
{
    int.Parse(l);
}
catch (FormatException)
{
    Console.WriteLine("Invalid input. Please enter 1, 2, or 3.");
}

As you can see, I have asked for input, but if the user enters a non-integral answer such as the letter "f", the catch statement catches it, but then throws the exception again afterwards, because the variable "l" still equals "f". Help?

like image 648
omni Avatar asked Dec 05 '25 10:12

omni


1 Answers

You can use int.TryParse instead of catching exceptions. It returns whether the parse was successful, so you can check it in a loop until the input is valid e.g.

int i;
bool valid = false;
do {
    Console.WriteLine("Enter an int: ");
    string input = Console.ReadLine();
    valid = int.TryParse(input, out i);
} while(! valid);

//use i
like image 154
Lee Avatar answered Dec 06 '25 23:12

Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!