[C#] Applying Try Catch in this Statements

Joined
Nov 24, 2004
Messages
147
Reaction score
2
Anyhow know how to apply Try Catch for Invalid FormatException in this statements?

do
{

Console.Write("Enter number: ");
test = int.Parse(Console.ReadLine());

if (test <= 0 || test > 999)
{
Console.WriteLine("Test cannot be equal to 0 or greater than 999");
}

}
while (test <= 0 || test > 999)
 
Code:
bool isValid = false;

do
{
	Console.Write("Enter number: ");
	
	try
	{
		test = int.Parse(Console.ReadLine());
	} 
	catch (FormatException fe) { Console.WriteLine(fe.Message); }

	if (test <= 0 || test > 999)
		Console.WriteLine("Test cannot be equal to 0 or greater than 999");
	else
		isValid = true;

}
while (!isValid)
 
Last edited:
Back