JCdeveloper
JCdeveloper

Reputation: 3

Exception handling with a while loop

So in my car store program I've been trying to find a way to throw an exception when people enter an invalid character more than one time, so I decided to try and use a while loop for when the Console.ReadLine() == null, but can't quite seem to figure it out. Thanks for the help. I only included a snippet of my attempt at a try catch with the while loop.

Console.Out.WriteLine("What is the car make? Toyota, Ford, etc.");

carMake = Console.ReadLine();

Console.Out.WriteLine("What is the car model? Corvette, Focus, etc.");

carModel = Console.ReadLine();

Console.Out.WriteLine("What is the car price? Only numbers please.");
                        
try
{
carPrice = int.Parse(Console.ReadLine());
}
                    
catch

{
while (Console.ReadLine() == null)
{

Console.Out.WriteLine("You must ONLY enter numbers");

carPrice = int.Parse(Console.ReadLine());

}
}

Upvotes: 0

Views: 129

Answers (1)

JonasH
JonasH

Reputation: 36371

Use TryParse instead of parse, removing the need for exception handling:

Console.WriteLine("What is the car price? Only numbers please.");
while(!int.TryParse(Console.ReadLine(), out var carPrice)){
    Console.Out.WriteLine("You must ONLY enter numbers");
}

It might also be a good idea to put a code fragment like that into a helper function to read numbers from the console.

Upvotes: 3

Related Questions