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("这里是必须执行的"); } } }
运行结果:

浙公网安备 33010602011771号