如何在程序捕获异常后使程序重复?

问题描述 投票:4回答:1

我希望程序在获得格式异常后重复。

相反,它只是继续。我怎么重复它?

例如,它应该在异常后打印错误消息,然后重复该程序直到用户符合。

我试图把try catch放在do while循环中但是它使我的numAge var局部并显示错误。

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");
c# exception try-catch
1个回答
2
投票

只需将try-catch块移动到循环内部而不是外部:

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);
© www.soinside.com 2019 - 2024. All rights reserved.