try{} catch{}语句检测错误
以前如果用户输错了,程序就停止了。现在要用try-catch语句实现即便输错了,还是可以重新输入。
static void Main(string[] args)
{
int n1 = 0,n2 = 0;
while (true)
{
try
{
n1 = Convert.ToInt32(Console.ReadLine());
n2 = Convert.ToInt32(Console.ReadLine());
break;
}
catch
{
Console.WriteLine("输入的数据不符合规则,请重新输入");
}
}
Console.WriteLine(n1 + n2);
}