我希望程序在获得格式异常后重复。
相反,它只是继续。我怎么重复它?
例如,它应该在异常后打印错误消息,然后重复该程序直到用户符合。
我试图把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");
只需将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);