C#异常相关关键字:Exceptions,throw,try,catch,finally

📅 2026/7/24 17:47:08 👁️ 阅读次数 📝 编程学习
C#异常相关关键字:Exceptions,throw,try,catch,finally

一.异常Exceptions

1.1 异常概述

异常就是运行时错误(报错),它会打断程序的执行流程,位于产生异常的代码之后的语句不会执行

1.2 异常原因

  1. 语句throw会立即无条件地抛出异常
  2. 某些语句/表达式在算不下去、做不成时(比如除以0,访问数字下标-1),运行时会自己抛异常

1.3System.Exception类

System.Exception是所有异常的基类,其Message属性包含异常的描述信息

1.4 常见异常类

异常类型描述
System.ArithmeticException算术运算期间发生的异常的基类,例如System.DivideByZeroExceptionSystem.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 catch

try-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); }

三.throw

throw语句用来主动触发异常,执行throw后会产生报错,后面语句不再执行,throw有两种用法

3.1 throw e

throw后面加一个Exceptions异常对象,eg

throw new ArithmeticException();

3.2 在catch中调用throw;

try-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 finally

try-finally语法:无异常执行完try块时,finally块将执行

try { int a = 1; int b = 1; int c = a / b; } finally { Debug.Log("run finally"); }

五.try catch finally

try-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"); }