
一.异常Exceptions1.1 异常概述异常就是运行时错误(报错)它会打断程序的执行流程位于产生异常的代码之后的语句不会执行1.2 异常原因语句throw会立即无条件地抛出异常某些语句/表达式在算不下去、做不成时(比如除以0访问数字下标-1)运行时会自己抛异常1.3System.Exception类System.Exception是所有异常的基类其Message属性包含异常的描述信息1.4 常见异常类异常类型描述System.ArithmeticException算术运算期间发生的异常的基类例如System.DivideByZeroException和System.OverflowException。System.ArrayTypeMismatchException当存储到数组失败时抛出因为存储元素的类型与数组的类型不兼容。System.DivideByZeroException当尝试将整数值除以零时抛出。System.IndexOutOfRangeException当尝试通过小于零或超出数组边界的索引来索引数组时抛出。System.InvalidCastException当从基类型或接口到派生类型的显式转换在运行时失败时抛出。System.InvalidOperationException当方法调用对于对象的当前状态无效时抛出。System.NullReferenceExceptionnull当引用的使用方式导致需要引用的对象时抛出。System.OutOfMemoryException当尝试分配内存通过new失败时抛出。System.OverflowException当上下文中的算术运算checked溢出时抛出。System.StackOverflowException当执行堆栈由于有太多挂起的调用而耗尽时抛出通常表示非常深或无限的递归。System.TypeInitializationException当静态构造函数或静态字段初始值设定项引发异常且不catch存在任何子句来捕获该异常时抛出。参考Exceptions二.try catchtry-catch语法用来应对发生异常后的处理具体语法是在try块中发生异常后逐个匹配catch中的类型匹配成功则执行对应的catch块try { int a 1; int b 0; int c a / b; } catch (IndexOutOfRangeException e) { Debug.Log(捕获到异常IndexOutOfRangeException: e.Message); } catch (ArithmeticException e) { Debug.Log(捕获到异常ArithmeticException: e.Message); } catch (Exception e) { Debug.Log(捕获到异常Exception: e.Message); }三.throwthrow语句用来主动触发异常执行throw后会产生报错后面语句不再执行throw有两种用法3.1 throw ethrow后面加一个Exceptions异常对象egthrow new ArithmeticException();3.2 在catch中调用throwtry-catch语句中若没有throw则不会产生报错若要显示报错在catch语句块中执行throw即可注意throw后面没有异常对象直接跟分号try { int a 1; int b 0; int c a / b; } catch (ArithmeticException e) { Debug.Log(捕获到异常ArithmeticException: e.Message); throw; }Tip用throw e替代throw可以但不推荐建议统一按throw;来写参考异常处理语句四.try finallytry-finally语法无异常执行完try块时finally块将执行try { int a 1; int b 1; int c a / b; } finally { Debug.Log(run finally); }五.try catch finallytry-catch-finally一起使用时finally将在catch之后执行try { int a 1; int b 0; int c a / b; } catch (ArithmeticException e) { Debug.Log(捕获到异常ArithmeticException: e.Message); throw; } finally { Debug.Log(run finally); }