C#入门11.4——预定义异常类(1)

来源:互联网 发布:西部数码域名查询 编辑:程序博客网 时间:2024/05/22 06:19

异常类 说明 

Exception 所有异常对象的基类

SystemException 运行时产生的所有错误的基类

IndexOutOfRangeException 当一个数组的下标超出范围时运行时引发

NullReferenceException 当一个空对象被引用时运行时引发 

ArgumentException 所有参数异常的基类


using System;using System.Collections.Generic;public class MyClass{public static void RunSnippet(){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());}}}

1
2
3
4
5
6
7
8
9
0
索引超出了数组界限。

using System;using System.Collections.Generic;public class MyClass{public static void RunSnippet(){<span style="white-space:pre"></span>string mystr=null;<span style="white-space:pre"></span>try<span style="white-space:pre"></span>{<span style="white-space:pre"></span>Console.WriteLine(mystr.ToString());
}catch (NullReferenceException ex){Console.WriteLine(ex.Message.ToString());}}
}


using System;using System.Collections.Generic;public class MyClass{static int DivideByTwo(int num){if(num%2==1)throw new ArgumentException("此处必须为偶数","num");return num/2;}public static void RunSnippet(){try{Console.WriteLine(DivideByTwo(9));}catch(ArgumenException){Console.WriteLine("9不能被2整除");}}}}


0 0
原创粉丝点击