bubblepop
bubblepop

Reputation: 43

How do I make a program repeat itself after it catches an exception?

I want the program to repeat itself after it gets a format exception.

Instead it just continues. How do I make it repeat?

For example it should print the error message after an exception and then repeat the program till the user complies.

I tried to put the try catch inside the do while loop but it make my numAge var local and showed an error.

int numAge;

try
{
    do
    {
        Console.WriteLine("Enter your age");
        numAge = int.Parse(Console.ReadLine ());
    } while (numAge < 0);
}
catch (FormatException err)
{
    Console.WriteLine(err.Messagec + "Please try again");
    //how do I actually make it try again?
}

Console.WriteLine("Program continues");

Upvotes: 4

Views: 240

Answers (1)

Mureinik
Mureinik

Reputation: 311228

Just move the try-catch block inside the loop instead of outside it:

do {
    try
    {
        Console.WriteLine("Enter your age");
        numAge = int.Parse(Console.ReadLine());
    }
    catch (FormatException err)
    {
        numAge = -1;
        Console.WriteLine(err.Messagec+ "Please try again");
    }
} while (numAge < 0);

Upvotes: 2

Related Questions