异常处理
try/catch/finally、throw、自定义异常、using 自动释放
异常处理
C# 异常和 Java 类似,但多了 using 语句(自动 IDisposable)、异常过滤器 when。
学完本章你将: 掌握 try/catch/finally、throw、自定义异常、using。
try / catch / finally
csharp
try
{
int result = Divide(10, 0);
Console.WriteLine(result);
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"除零错误:{ex.Message}");
}
catch (Exception ex) when (ex.Message.Contains("timeout"))
{
Console.WriteLine("超时异常,可重试");
}
catch (Exception ex)
{
Console.WriteLine($"其他错误:{ex.Message}");
throw; // 重新抛出,保留原始堆栈
}
finally
{
Console.WriteLine("无论异常与否,都会执行");
}
自定义异常
csharp
public class ValidationException : Exception
{
public IEnumerable<string> Errors { get; }
public ValidationException(
string message,
IEnumerable<string>? errors = null) : base(message)
{
Errors = errors ?? Array.Empty<string>();
}
}
// 使用
throw new ValidationException("验证失败",
new[] { "姓名不能为空", "邮箱格式不正确" });
using —— 自动释放资源
csharp
// using 声明(C# 8+)—— 离开作用域自动 Dispose
using var file = File.OpenWrite("data.txt");
// ... 写文件 ...
// 离开时自动调用 file.Dispose()
// using 语句块(旧式)
using (var file = File.OpenWrite("data.txt"))
{
// ... 写文件 ...
}