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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With