C# 异常处理详解

发布时间:2026/7/13 12:46:14
C# 异常处理详解 异常处理Exception Handling是 C# 中非常重要的知识点它能够让程序在发生错误时不会直接崩溃而是通过捕获异常进行处理提高程序的稳定性和用户体验。一、什么是异常Exception异常Exception是程序运行过程中发生的错误。例如除数为 0数组越界文件不存在数据库连接失败网络连接失败空对象调用成员例如int a 10; int b 0; Console.WriteLine(a / b);运行结果Unhandled Exception: System.DivideByZeroException程序直接终止。二、为什么需要异常处理如果没有异常处理程序开始 ↓ 发生错误 ↓ 程序退出加入异常处理程序开始 ↓ 发生错误 ↓ 捕获异常 ↓ 记录日志 ↓ 提示用户 ↓ 继续运行因此异常处理的目的不是消除错误而是优雅地处理错误。三、try-catch最基本的异常处理方式。语法try { // 可能发生异常的代码 } catch { // 处理异常 }例如try { int a 10; int b 0; Console.WriteLine(a / b); } catch { Console.WriteLine(发生异常); }输出发生异常程序不会崩溃。四、捕获异常对象可以获取详细错误信息。try { int a 10; int b 0; Console.WriteLine(a / b); } catch (Exception ex) { Console.WriteLine(ex.Message); }输出Attempted to divide by zero.其中ex就是异常对象。五、Exception对象常用属性例如catch(Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); Console.WriteLine(ex.Source); }常见属性属性说明Message错误信息StackTrace调用堆栈Source异常来源InnerException内部异常HelpLink帮助链接TargetSite出错的方法例如catch(Exception ex) { Console.WriteLine(错误 ex.Message); Console.WriteLine(位置 ex.StackTrace); }六、多个catch不同异常可以分别处理。例如try { int[] arr {1,2,3}; Console.WriteLine(arr[5]); } catch (IndexOutOfRangeException) { Console.WriteLine(数组越界); } catch (Exception) { Console.WriteLine(未知错误); }输出数组越界原则子类异常放前面父类异常放最后。错误写法catch(Exception) { } catch(IndexOutOfRangeException) { }因为Exception已经把所有异常都捕获了。七、finallyfinally 无论是否发生异常都会执行。语法try { } catch { } finally { }例如try { Console.WriteLine(开始); int a 10; int b 0; Console.WriteLine(a / b); } catch { Console.WriteLine(发生异常); } finally { Console.WriteLine(结束); }输出开始 发生异常 结束八、finally的用途主要用于释放资源。例如FileStream fs null; try { fs new FileStream(test.txt, FileMode.Open); } catch { } finally { if (fs ! null) { fs.Close(); } }即使发生异常文件也会关闭九、using代替finally现代 C# 推荐使用using (FileStream fs new FileStream(test.txt, FileMode.Open)) { // 使用文件 }等价于try { } finally { Dispose() }更推荐使用using var fs new FileStream(test.txt, FileMode.Open); // 使用文件离开作用域后自动释放资源。十、throw抛出异常可以主动抛出异常。throw new Exception(发生错误);例如Console.Write(请输入年龄); int age int.Parse(Console.ReadLine()); if (age 0) { throw new Exception(年龄不能小于0); }程序年龄不能小于0十一、自定义异常建议继承 Exception。public class AgeException : Exception { public AgeException(string msg) : base(msg) { } }使用if(age0) { throw new AgeException(年龄错误); }捕获catch(AgeException ex) { Console.WriteLine(ex.Message); }十二、throw 与 throw ex 的区别很多初学者容易写成catch(Exception ex) { throw ex; }实际上应该写catch(Exception ex) { throw; }区别throw保留原始异常位置。原始位置 ↓ 继续抛出便于定位问题。throw ex重新创建调用栈。catch这里 ↓ 新的异常位置原始调用位置会丢失。推荐throw;十三、异常过滤Exception FilterC# 支持使用when对异常进行条件过滤。try { // ... } catch (Exception ex) when (ex.Message.Contains(网络)) { Console.WriteLine(网络异常); }这样可以在进入catch前根据条件决定是否处理异常。十四、常见异常类型异常说明Exception所有异常基类NullReferenceException空引用DivideByZeroException除零IndexOutOfRangeException数组越界FormatException格式错误InvalidCastException类型转换失败OverflowException数值溢出FileNotFoundException文件不存在IOExceptionIO异常UnauthorizedAccessException权限不足TimeoutException超时ArgumentException参数错误ArgumentNullException参数为空InvalidOperationException非法操作十五、实际开发案例文件读取try { string text File.ReadAllText(data.txt); Console.WriteLine(text); } catch (FileNotFoundException) { Console.WriteLine(文件不存在); } catch (UnauthorizedAccessException) { Console.WriteLine(没有权限访问文件); } catch (IOException ex) { Console.WriteLine($IO错误{ex.Message}); }数据转换try { Console.Write(请输入数字); int number int.Parse(Console.ReadLine()); Console.WriteLine(number); } catch (FormatException) { Console.WriteLine(请输入正确的数字); } catch (OverflowException) { Console.WriteLine(数字超出范围); }十六、异常处理最佳实践只捕获能够处理的异常不要为了“防止报错”而滥用catch (Exception)。避免空的catch块至少记录日志或输出必要信息。优先使用具体异常类型如FileNotFoundException最后再捕获Exception。使用using或using var管理实现了IDisposable的资源不要依赖手动释放。需要重新抛出异常时使用throw;保留完整的调用堆栈。不要把异常当作正常业务流程例如用异常判断用户输入是否合法异常应只用于真正的异常情况。在公共 API 中提供清晰、有意义的异常信息便于调用方定位问题。记录详细日志异常类型、消息、堆栈、上下文方便排查线上问题。十七、知识总结异常处理 │ ├── try ├── catch │ ├── Exception │ ├── 多个catch │ └── when过滤 ├── finally ├── using ├── throw ├── 自定义异常 ├── throw 与 throw ex ├── 常见异常类型 └── 最佳实践学习建议掌握异常处理后建议继续学习以下 C# 核心内容委托Delegate事件EventLambda 表达式LINQ 查询泛型Generic进阶异步编程async / await文件与流IO反射Reflection特性Attribute依赖注入Dependency Injection这些知识与异常处理结合使用是开发 WinForms、WPF、ASP.NET Core 和企业级应用的基础。