题目描述
预定义异常类。(控制台应用程序)
异常类 | 说明 |
Exception | 所有异常对象的基类 |
SystemException | 运行时产生的所有错误的基类 |
IndexOutOfRangeException | 当数组的下标超出范围时运行引发异常 |
NullReferenceException | 当一个空对象被引用时运用时引发 |
ArgumentException | 所有参数异常的基类 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 预定义异常类 { class Program { static void Main(string[] args) { 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()); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 预定义异常类 { class Program { static void Main(string[] args) { string mystr = null; try { Console.WriteLine(mystr.ToString()); } catch (NullReferenceException ex) { Console.WriteLine(ex.Message.ToString()); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 预定义异常类 { class Program { static int DivideByTwo(int num) { if (num % 2 == 1) throw new ArgumentException("此处必须为偶数","num"); return num / 2; } static void Main(string[] args) { try { Console.WriteLine(DivideByTwo(9)); } catch (ArgumentException ex) { Console.WriteLine(ex.Message.ToString()); } } } }