代码段——捕获异常后尝试指定次数

        public void Test()
        {
            bool isSuccess = false;
            int i = 1;
            while (!isSuccess)
            {
                if (i <= 3)
                {
                    try
                    {
                        Console.WriteLine($"尝试第{i}");
                        Do(i);
                        isSuccess = true;
                    }
                    catch (Exception)
                    { 
                        i++;
                        isSuccess = false;                       
                    }
                }
                else
                {
                    Console.WriteLine("尝试三次,依旧未成功");
                    break;
                }
            }
        }

        public void Do(int i)
        {
            if (i <= 2)
            {
                throw new Exception("my error");
            }
            else
            {
                Console.WriteLine("这是第3次,成功运行");
            }
        }
posted @ 2023-09-21 16:15  shanzm  阅读(1)  评论(0编辑  收藏  举报
TOP