蓝色天空.知识 · 实践 · 创造
我的收藏
C# 教程目录 42章
C# / LEARN BY DOING

C# 异常处理

系统讲解 C# 结构化异常处理四关键字(try、catch、finally、throw)、System.Exception 继承体系与 8 类内置系统异常、自定义异常设计及重新抛出堆栈保留机制,并附本地 csc.exe (.NET Framework 4.x) 实测。

学完这一章,你能够

  • 系统讲解 C# 结构化异常处理四关键字(try、catch、finally、throw)、System.Exception 继承体系与 8 类内置系统异常、自定义异常设计及重新抛出堆栈保留机制,并附本地 csc.exe (.NET Framework 4.x) 实测。

异常处理机制与四个核心关键字

异常表示程序运行期间发生的非预期故障(例如整数除以零或访问无效索引),它通过结构化的控制流转移机制将错误检测与错误处理解耦。C# 异常处理围绕四个关键字展开:`try` 标识可能引发异常的受保护代码块,后接一个或多个 `catch` 块或 `finally` 块;`catch` 按异常类型匹配并接管错误处理;`finally` 定义无论是否发生异常都会执行的收尾逻辑(常用于关闭文件句柄、释放连接或锁资源);`throw` 用于主动抛出新的异常对象或将当前异常继续向上层传播。

标准 `try/catch/finally` 结构允许依次编写多个 `catch` 子句以区分不同异常类型。由于运行时按自上而下的声明顺序进行类型匹配,派生度更具体的异常类(如 `ArgumentNullException`)必须排在基类(如 `ArgumentException` 或 `Exception`)之前,否则后续更具体的分支会因不可达而触发编译错误。

System.Exception 继承体系与常见预定义异常

C# 中所有异常对象都直接或间接继承自 `System.Exception`。早期 .NET 类库将异常大致划分为两支:由运行时或基类库抛出的系统异常基类 `System.SystemException`,以及面向应用层错误的 `System.ApplicationException`。需特别补充现代 .NET 官方设计规范:由于 `ApplicationException` 在实践中并未形成稳定边界,微软官方现推荐自定义业务异常直接继承 `System.Exception`(同时保留对历史代码继承 `ApplicationException` 的兼容理解)。下表列出 8 个常见的预定义 `SystemException` 派生异常类。

try/catch/finally 实测、自定义异常与重新抛出勘误

借助结构化异常处理,核心业务逻辑可以与容错恢复清晰隔离。以整数除法 `DivNumbers.Division(25, 0)` 为例,除数为零时 CLR 抛出 `DivideByZeroException`,控制流转入对应 `catch` 块处理错误,随后仍必定进入 `finally` 块完成收尾;而在正常调用 `Division(25, 5)` 时跳过 `catch`,同样执行 `finally`。本站本地 `csc.exe` 实测确认异常路径返回默认值 `0`(捕获标志 `True`、收尾标志 `True`),正常路径返回 `5`(捕获标志 `False`、收尾标志 `True`)。

当内置异常不足以表达业务领域语义时,可自定义异常类并调用 `base(message)` 传递错误说明(例如当温度为 `0` 时抛出 `TempIsZeroException("Zero Temperature found")`)。实测核对直接继承 `Exception` 的 `TempIsZeroException` 与兼容继承 `ApplicationException` 的 `LegacyAppTempException` 均可正常捕获并读取 `Message`,二者最终均派生自 `System.Exception`。

在 `catch` 块内可以将捕获到的异常对象继续向上抛出,但需重点订正两处常见写法错误:第一,C# 区分大小写,关键字必须小写为 `catch` 与 `throw` 且语句末尾带分号;第二,在 `catch` 内直接写裸 `throw;` 会完整保留原始异常发生位置的调用栈帧(实测 `StackTrace` 仍包含内层 `InnerFault`),而写成 `throw ex;` 会重置堆栈跟踪起点并丢失内层调用现场,工程中重新抛出当前异常应优先使用 `throw;`。

常见预定义 SystemException 异常类对照表

异常类触发场景与作用说明实测与边界备注
`System.IO.IOException`文件、目录或底层流读写失败时引发的 I/O 异常基类已在本地实测捕获;常见子类含 `FileNotFoundException`
`System.IndexOutOfRangeException`访问数组或集合下标小于 `0` 或大于等于长度时抛出实测访问长度 1 数组的 `[3]` 精确触发
`System.ArrayTypeMismatchException`向协变引用数组写入与实际元素类型不兼容的对象时抛出实测向 `object[] arr = new string[1]` 写入 `42` 精确触发
`System.NullReferenceException`对值为 `null` 的引用调用成员或访问属性时抛出实测访问空字符串 `Length` 精确触发
`System.DivideByZeroException`整数或 `decimal` 类型除以零时抛出浮点 `double`/`float` 除以零得 `Infinity`/`NaN` 而非此异常
`System.InvalidCastException`运行期显式类型转换或拆箱失败时抛出实测将装箱字符串强转为 `int` 精确触发
`System.OutOfMemoryException`托管堆或进程地址空间内存耗尽无法继续分配时抛出反射确认派生自 `SystemException`;避免在单测中刻意耗尽进程内存
`System.StackOverflowException`调用栈帧深度耗尽(如无限递归)时由运行时引发自 .NET 2.0 起默认不可被常规 `catch` 捕获而直接终止进程,反射确认其派生自 `SystemException`

运行 csc.exe (.NET Framework 4.x) 结构化异常处理、堆栈保留与预定义异常实测

含完整源码 · 230 行
展开查看收起
csharp
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace CSharpExceptionHandlingLab
{
    public class TempIsZeroException : Exception
    {
        public TempIsZeroException(string message) : base(message)
        {
        }
    }

    public class LegacyAppTempException : ApplicationException
    {
        public LegacyAppTempException(string message) : base(message)
        {
        }
    }

    internal class DivNumbers
    {
        private int result;
        public bool FinallyExecuted { get; private set; }
        public bool CaughtDivideByZero { get; private set; }

        public DivNumbers()
        {
            result = 0;
        }

        public int Division(int num1, int num2)
        {
            FinallyExecuted = false;
            CaughtDivideByZero = false;
            result = 0;
            try
            {
                result = num1 / num2;
            }
            catch (DivideByZeroException)
            {
                CaughtDivideByZero = true;
            }
            finally
            {
                FinallyExecuted = true;
            }
            return result;
        }
    }

    internal class TemperatureSensor
    {
        private int temperature;

        public TemperatureSensor(int value)
        {
            temperature = value;
        }

        public string CheckTemp()
        {
            if (temperature == 0)
            {
                throw new TempIsZeroException("Zero Temperature found");
            }
            return string.Format("Temperature: {0}", temperature);
        }
    }

    internal class Program
    {
        private static void InnerFault()
        {
            throw new InvalidOperationException("inner-boom");
        }

        private static void RethrowPreserve()
        {
            try
            {
                InnerFault();
            }
            catch (InvalidOperationException)
            {
                throw;
            }
        }

        private static void RethrowReset()
        {
            try
            {
                InnerFault();
            }
            catch (InvalidOperationException ex)
            {
                throw ex;
            }
        }

        private static string Esc(string s)
        {
            if (s == null) return "null";
            StringBuilder sb = new StringBuilder("\"");
            foreach (char c in s)
            {
                switch (c)
                {
                    case '\\': sb.Append("\\\\"); break;
                    case '"': sb.Append("\\\""); break;
                    case '\n': sb.Append("\\n"); break;
                    case '\r': sb.Append("\\r"); break;
                    case '\t': sb.Append("\\t"); break;
                    default:
                        if (c < 32) sb.AppendFormat("\\u{0:x4}", (int)c);
                        else sb.Append(c);
                        break;
                }
            }
            sb.Append("\"");
            return sb.ToString();
        }

        private static string CaseJson(string name, string summary, string expected, string actual)
        {
            bool passed = string.Equals(expected, actual, StringComparison.Ordinal);
            return string.Format(
                "{{\"name\":{0},\"summary\":{1},\"expected\":{2},\"actual\":{3},\"passed\":{4}}}",
                Esc(name), Esc(summary), Esc(expected), Esc(actual), passed ? "true" : "false"
            );
        }

        public static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;
            List<string> cases = new List<string>();

            // Case 1: try/catch/finally divide by zero
            DivNumbers div = new DivNumbers();
            int rErr = div.Division(25, 0);
            bool errCaught = div.CaughtDivideByZero;
            bool errFin = div.FinallyExecuted;
            int rOk = div.Division(25, 5);
            bool okCaught = div.CaughtDivideByZero;
            bool okFin = div.FinallyExecuted;
            string actual1 = string.Format("err={0}/{1}/{2};ok={3}/{4}/{5}", rErr, errCaught, errFin, rOk, okCaught, okFin);
            cases.Add(CaseJson(
                "try_catch_finally_divide_by_zero",
                "Verify try/catch handles DivideByZeroException and finally executes on both exception and normal paths",
                "err=0/True/True;ok=5/False/True",
                actual1
            ));

            // Case 2: custom exception & hierarchy
            string caughtMsg = "";
            try
            {
                new TemperatureSensor(0).CheckTemp();
            }
            catch (TempIsZeroException ex)
            {
                caughtMsg = ex.Message;
            }
            string okMsg = new TemperatureSensor(25).CheckTemp();
            bool legacyIsEx = typeof(LegacyAppTempException).IsSubclassOf(typeof(ApplicationException))
                && typeof(ApplicationException).IsSubclassOf(typeof(Exception));
            bool modernIsEx = typeof(TempIsZeroException).IsSubclassOf(typeof(Exception));
            string actual2 = string.Format("{0}|{1}|legacy={2}|modern={3}", caughtMsg, okMsg, legacyIsEx, modernIsEx);
            cases.Add(CaseJson(
                "custom_exception_hierarchy",
                "Verify custom exception throwing/catching and Exception vs ApplicationException inheritance",
                "Zero Temperature found|Temperature: 25|legacy=True|modern=True",
                actual2
            ));

            // Case 3: rethrow stack trace preservation & multi-catch ordering
            bool preserveHasInner = false;
            try { RethrowPreserve(); }
            catch (InvalidOperationException ex)
            {
                preserveHasInner = ex.StackTrace != null && ex.StackTrace.IndexOf("InnerFault", StringComparison.Ordinal) >= 0;
            }
            bool resetLosesInner = false;
            try { RethrowReset(); }
            catch (InvalidOperationException ex)
            {
                resetLosesInner = ex.StackTrace != null && ex.StackTrace.IndexOf("InnerFault", StringComparison.Ordinal) < 0;
            }
            string multiMatch = "";
            try { throw new ArgumentNullException("p"); }
            catch (ArgumentNullException) { multiMatch = "specific"; }
            catch (ArgumentException) { multiMatch = "base"; }
            string actual3 = string.Format("preserve={0};resetNoInner={1};multi={2}", preserveHasInner, resetLosesInner, multiMatch);
            cases.Add(CaseJson(
                "rethrow_stack_trace_preservation",
                "Verify bare throw preserves original stack frame while throw ex resets it, plus specific-before-general catch order",
                "preserve=True;resetNoInner=True;multi=specific",
                actual3
            ));

            // Case 4: predefined SystemException subclasses
            List<string> triggered = new List<string>();
            try { throw new IOException("io-sim"); } catch (IOException) { triggered.Add("IO"); }
            try { int[] a = new int[1]; int x = a[3]; Console.Write(x); } catch (IndexOutOfRangeException) { triggered.Add("Index"); }
            try { object[] arr = new string[1]; arr[0] = 42; } catch (ArrayTypeMismatchException) { triggered.Add("ArrayType"); }
            try { string s = null; int len = s.Length; Console.Write(len); } catch (NullReferenceException) { triggered.Add("NullRef"); }
            try { int z = 0; int y = 10 / z; Console.Write(y); } catch (DivideByZeroException) { triggered.Add("DivZero"); }
            try { object o = "abc"; int n = (int)o; Console.Write(n); } catch (InvalidCastException) { triggered.Add("Cast"); }
            bool oomSys = typeof(OutOfMemoryException).IsSubclassOf(typeof(SystemException));
            bool soSys = typeof(StackOverflowException).IsSubclassOf(typeof(SystemException));
            string actual4 = string.Join(",", triggered.ToArray()) + string.Format(";OOM={0};SO={1}", oomSys, soSys);
            cases.Add(CaseJson(
                "system_exception_types_runtime",
                "Verify 6 catchable SystemException subclasses at runtime and confirm OutOfMemoryException/StackOverflowException derive from SystemException",
                "IO,Index,ArrayType,NullRef,DivZero,Cast;OOM=True;SO=True",
                actual4
            ));

            Console.WriteLine(string.Format(
                "{{\"version\":\"csc4/{0}\",\"cases\":[{1}]}}",
                Environment.Version.ToString(),
                string.Join(",", cases.ToArray())
            ));
        }
    }
}
核对除零捕获与 finally 双路径执行、自定义异常继承与消息传递、裸 throw 与 throw ex 堆栈差异及 8 类 SystemException 行为全部通过。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1321.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:C#

课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a1321.zip

下载课程关联工程包:C#

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1333.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

裸 `throw;` 会原样保留异常最初抛出位置的调用栈信息;而 `throw ex;` 会将异常堆栈重置到当前 `catch` 所在行,抹去内层真实故障点的调用栈帧,因此重新抛出原异常时应使用 `throw;`。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习