C#小白学习笔记(13)捕捉异常

        static void Main(string[] args)
        {
            int[] age = { 12, 45, 70, 34 };
            while (true)
            {
                Console.WriteLine("请输入索引:");
                int index = int.Parse(Console.ReadLine());
                try  //抛出异常(可能出现异常的语句)可以有一个try块,多个catch块
                {
                    Console.WriteLine(age[index]);
                }
                catch (Exception ex) //处理异常,Exception是所有异常的基类
                {
                    Console.WriteLine("请输入0-3之间的数字");
                }
                finally //始终会处理的代码
                {
                    Console.WriteLine("这里是必须执行的");
                }
            }
        }

运行结果:

 

posted @ 2020-09-24 09:51  ___lucky  阅读(106)  评论(0)    收藏  举报