C# 错误处理简介
在任何应用程序中,尤其是在基于 .NET 平台的复杂企业系统中,错误是不可避免的。用户可能输入无效数据,文件可能无法访问,网络连接可能中断。与其让程序意外终止,优秀的开发者会使用异常处理机制。
在 C# 中,该机制的基础是 try/catch/finally 结构。然而,语言的能力远不止于此:还有 using 和 throw 语句,以及创建自定义异常类型的能力。在本文中,我们将详细分析 C# (.NET) 中错误处理的所有关键方面,使您的代码不仅可靠,而且可读性强。
1. 基本结构:try, catch 和 finally
这是认识异常的起点。try 块包含可能引发错误的代码。catch 块捕获异常并处理它。finally 块无论是否发生错误都会执行——它非常适合释放资源(关闭文件、连接)。
语法和示例
using System;using System.IO;
class Program{ static void Main() { try { Console.Write("请输入文件路径:"); string path = Console.ReadLine(); string content = File.ReadAllText(path); Console.WriteLine("文件内容:"); Console.WriteLine(content); } catch (FileNotFoundException ex) { Console.WriteLine($"错误:文件未找到。{ex.Message}"); } catch (UnauthorizedAccessException ex) { Console.WriteLine($"错误:无文件访问权限。{ex.Message}"); } catch (Exception ex) // 捕获所有其他异常 { Console.WriteLine($"未知错误:{ex.Message}"); } finally { Console.WriteLine("finally 块已执行。释放资源(如果需要)。"); } }}重要事项:
- catch 块的顺序很重要:首先应捕获更具体的异常(例如
FileNotFoundException),然后是更通用的异常(Exception)。如果将通用块放在前面,则永远不会执行到更具体的块。 - finally 块不是必需的。如果您不需要保证释放资源,可以省略它。
- 不要无必要地捕获
Exception。如果您不知道如何处理错误,最好让程序崩溃——这有助于在开发阶段发现问题。
2. 使用 using 释放资源
虽然 finally 是一个强大的工具,但每次为关闭文件或数据库连接等操作编写它很繁琐。对于实现 IDisposable 接口的对象,C# 提供了 using 语句。它保证在退出块时调用 Dispose() 方法,即使发生异常也是如此。
方法对比
不使用 using(手动释放):
StreamReader reader = null;try{ reader = new StreamReader("data.txt"); string line = reader.ReadLine(); // ... 使用 reader 进行操作}finally{ if (reader != null) reader.Dispose();}使用 using:
using (StreamReader reader = new StreamReader("data.txt")){ string line = reader.ReadLine(); // ... 使用 reader 进行操作}// Dispose() 将被自动调用