1 class Program 2 { 3 static void Main(string[] args) 4 { 5 6 try 7 { 8 int.Parse(":"); 9 } 10 catch (Exception) 11 { 12 var ex = new MyException("输入的字符串中不是数字类型"); 13 throw ex; //抛出异常 14 } 15 16 } 17 18 19 } 20 21 22 [Serializable] //声明为可序列化的 因为要写入文件中 23 24 class MyException:System.ApplicationException 25 { 26 //三个构造函数:一个无参构造函数;一个字符串参数的构造函数;一个字符串参数,一个内部异常作为参数的构造函数 27 28 private string error; 29 private Exception innerException; 30 31 //无参数构造函数 32 public MyException() 33 { 34 35 } 36 37 //带一个字符串参数的构造 38 //z作用:当程序员用Excption类获取异常信息而非MyException时,把自定义的异常信息传递过去 39 public MyException(string msg):base(msg) 40 { 41 this.error = msg; 42 } 43 44 //带有一个字符串数和一个内部异常信息参数的构造函数 45 public MyException(string msg, Exception innerException) 46 : base(msg) 47 { 48 this.innerException = innerException; 49 this.error = msg; 50 } 51 52 //public string GetError() 53 //{ 54 // return error; 55 //} 56 }
C#_基础_简单实现自定义异常(十六)
猜你喜欢
转载自www.cnblogs.com/CeasarH/p/9171997.html
今日推荐
周排行