第15节、C#异常
1、C#异常
程序执行时遇到的错误或者意外行为就需要使用异常捕获,方便处理。
2、异常类:Exception
.Net framework类库中所有异常都派生于Exception类,常用的异常类如图所示
常用的系统异常类
异常类 | 说明 |
---|---|
System.NullReferenceException | 对象为空 |
Syetem.IndexOutOfRangeException | 数组越界 |
System.OutOfMemoryException | 用 new 分配内存失败 |
System.StackOverflowException | 递归过多、过深 |
System.ArithmaticException | 算术操作异常的基类 |
System.DivideByZeroException | 除零错误 |
3、异常处理语句
异常捕获格式:
try { 被监控的代码 } catch(异常类名 异常变量名) { 异常处理 }
- try:用于检测发生的异常,并帮助发送任何可能的异常
- catch:以处理错误,可以有多个cathc
- finally:无论是否引发异常,finally的代码都将被执行。
代码示例:
4、针对对应错误进行对应处理
5、C#自定义异常(throw抛出异常)
6、自定义异常(必须要继承Execption类)
声明异常语句格式:
class 异常类名:Exception { } 抛出自己定义的异常,调用格式如下 throw new 定义异常类名()
示例:
示例代码
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace ConsoleApplication1 8 { 9 public class 异常处理 10 { 11 public static void Main(string[] age) 12 { 13 try 14 { 15 //object obj = null; 16 ////obj只声明而已,值为Null,转换int型必定错误 17 //int number = (int)obj; 18 19 //int i = 5; 20 //int j = 0; 21 //int k = i / j; 22 string[] arry = { "小爱", "小美", "小丽" }; 23 for (int i = 0; i <=3;i++ ) 24 { 25 if(i==3) 26 { 27 //throw new Exception("数组长度仅是3,下标超出数组错误了"); 28 throw new MyException("数组长度仅是3,下标超出数组错误了"); 29 } 30 Console.WriteLine("你好,同学:"+arry[i]); 31 } 32 } 33 catch (NullReferenceException ex) 34 { 35 Console.WriteLine("未将对象引用到示例 "+ex.Message); 36 } 37 catch (DivideByZeroException ex) 38 { 39 Console.WriteLine("除零错误 "+ex.Message); 40 } 41 catch (IndexOutOfRangeException ex) 42 { 43 Console.WriteLine("数组越界 "+ex.Message); 44 } 45 finally 46 { 47 Console.ReadLine(); 48 } 49 } 50 51 /// <summary> 52 /// 自定义异常,继承Exception 53 /// </summary> 54 public class MyException : Exception 55 { 56 public MyException(string message) 57 : base(message) 58 { 59 60 } 61 } 62 } 63 64 }