欢迎光临散文网 会员登陆 & 注册

try{} catch{}语句检测错误

2023-01-31 00:03 作者:此城过客  | 我要投稿

以前如果用户输错了,程序就停止了。现在要用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);

}


try{} catch{}语句检测错误的评论 (共 条)

分享到微博请遵守国家法律