using System; using System.Collections.Generic; using System.Text; namespace V7._预定义异常类 { class Program { static int DivdeByTwo(int num) { if (num % 2 == 1) throw new ArgumentException("此处必须为偶数", "num"); return num / 2; } static void Main(string[] args) { //IndexOutOfRangeException 当一个数组的下标超出范围时运行引发 int[] myint ={1,2,3,4,5,6,7,8,9,0 }; try { for (int i = 0; i < 11; i++) { Console.WriteLine(myint[i]); } } catch (IndexOutOfRangeException exIOR) { Console.WriteLine(exIOR.Message.ToString()); } // NullReferenceException 当一个空对象被引用时运行发生 try { string mystr = null; Console.WriteLine(mystr.ToString()); } catch(NullReferenceException ex) { Console.WriteLine(ex.Message.ToString()); } //ArgumentException 所有参数异常的基类 try { Console.WriteLine(DivdeByTwo(9)); } catch (ArgumentException ex) { Console.WriteLine(ex.Message.ToString()); } Console.ReadKey(); } } }
|
|
来自: 时间剧毒 > 《第十一章:处理程序异常相关技术》