C Sharp 异常类型
外观
C#异常类型[编辑 | 编辑源代码]
C#异常类型是.NET框架中用于表示程序运行时错误的对象,它们继承自System.Exception
类。异常处理机制允许开发者捕获、处理和记录错误,从而提高程序的健壮性。本文将详细介绍C#中的主要异常类型及其使用场景。
异常基础[编辑 | 编辑源代码]
在C#中,当程序执行过程中发生意外情况(如除以零、空引用、文件不存在等)时,会抛出异常(throw exception)。异常对象包含错误信息、堆栈跟踪等数据,可通过try-catch-finally
块处理。
异常类层次结构[编辑 | 编辑源代码]
常见异常类型[编辑 | 编辑源代码]
1. System.SystemException[编辑 | 编辑源代码]
.NET运行时抛出的基类异常,通常表示不可恢复的系统级错误。
示例:NullReferenceException[编辑 | 编辑源代码]
当尝试访问空对象的成员时抛出:
string text = null;
try
{
Console.WriteLine(text.Length); // 抛出NullReferenceException
}
catch (NullReferenceException ex)
{
Console.WriteLine($"错误:{ex.Message}");
}
输出:
错误:Object reference not set to an instance of an object.
2. System.ArgumentException[编辑 | 编辑源代码]
当方法参数无效时抛出,其子类包括:
ArgumentNullException
- 参数为nullArgumentOutOfRangeException
- 参数超出有效范围
示例[编辑 | 编辑源代码]
void ValidateAge(int age)
{
if (age < 0)
throw new ArgumentOutOfRangeException(nameof(age), "年龄不能为负数");
}
try
{
ValidateAge(-5);
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine($"{ex.ParamName}: {ex.Message}");
}
输出:
age: 年龄不能为负数
3. System.IO.IOException[编辑 | 编辑源代码]
I/O操作失败时抛出,如文件访问错误。
实际案例:文件读取[编辑 | 编辑源代码]
try
{
string content = File.ReadAllText("nonexistent.txt");
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"文件未找到: {ex.FileName}");
}
catch (IOException ex)
{
Console.WriteLine($"IO错误: {ex.Message}");
}
自定义异常[编辑 | 编辑源代码]
可通过继承Exception
类创建自定义异常:
public class InsufficientFundsException : Exception
{
public decimal CurrentBalance { get; }
public decimal RequiredAmount { get; }
public InsufficientFundsException(decimal current, decimal required)
: base($"余额不足。当前余额: {current}, 需支付: {required}")
{
CurrentBalance = current;
RequiredAmount = required;
}
}
// 使用示例
try
{
throw new InsufficientFundsException(100m, 150m);
}
catch (InsufficientFundsException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine($"差额: {ex.RequiredAmount - ex.CurrentBalance}");
}
最佳实践[编辑 | 编辑源代码]
- 优先使用具体的异常类型而非基类
Exception
- 为可恢复的错误使用异常,而非控制程序流程
- 记录异常的
StackTrace
以便调试 - 自定义异常应提供有意义的错误信息
数学异常示例[编辑 | 编辑源代码]
计算平方根时处理ArgumentException
:
double SafeSqrt(double x)
{
if (x < 0)
throw new ArgumentException("输入不能为负数", nameof(x));
return Math.Sqrt(x);
}
总结表[编辑 | 编辑源代码]
异常类型 | 触发条件 | 典型场景 |
---|---|---|
NullReferenceException |
访问null对象成员 | 未初始化的对象 |
DivideByZeroException |
整数除以零 | 数学计算 |
IndexOutOfRangeException |
数组越界访问 | 集合操作 |
InvalidCastException |
无效类型转换 | 类型处理 |
FormatException |
格式解析失败 | 字符串转换 |