读代码,运行代码,学会理解异常代码的正确输出------>
运行结果:
学习代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ExceptionDemo { public class MyException : ApplicationException//自定义异常,异常的继承 { public MyException(string message): base(message){//要知道语法格式 } } class Program { static void Main(string[] args) { char input; while (true) { try { Console.Write("请输入一个字母(a-f),键入q以便退出:"); input = Convert.ToChar(Console.ReadLine());//接受输入的字符,注意语法格式 if (input == 'q') break; if (input < 'a' || input > 'f') throw new MyException("您输入的是" + input);//自定义异常处理 Console.WriteLine("输入的字母为" + input); } catch (MyException e) { Console.WriteLine("错误,应输入a-f之间的字母\n" + e.Message); } catch (Exception e) { Console.WriteLine("错误:" + e.Message); } finally//finally语句段不管上面的代码运不运行,都要执行 { Console.WriteLine("退出try语句块,finally必定会被执行"); } Console.WriteLine("--------------------------------------------"); } } } }