通过


CA2201:不要引发保留的异常类型

属性
规则 ID CA2201
标题 不要引发保留的异常类型
类别 使用情况
修复会引起中断还是不会引起中断 突发
在 .NET 10 中默认启用
适用的语言 C# 和 Visual Basic

原因

方法引发的异常类型太过笼统,或已由运行时保留。

规则说明

以下异常类型太过笼统,无法为用户提供足够的信息:

以下异常类型已保留,仅应由公共语言运行时引发:

请勿引发一般异常

如果在库或框架中引发一般异常类型,如 ExceptionSystemException,将强制使用者捕捉所有异常,包括不知该如何处理的未知异常。

相反,您可以抛出框架中已存在的更高级别的派生类型,或者创建您自己的从 Exception 派生的类型。

抛出特定异常

下表显示了对于各种类型的无效参数应抛出的异常,包括属性 set 访问器中的值参数。

参数无效 例外
null 参考 ArgumentNullException
超出允许的值(如集合或列表的索引)范围 ArgumentOutOfRangeException
enum 值无效 InvalidEnumArgumentException
包含不满足方法参数规范的格式(如适用于 ToString(String) 格式字符串) FormatException
否则无效 ArgumentException

下表显示了对于不同类型的无效操作所抛出的异常。

操作无效 例外
操作对对象的当前状态无效。 InvalidOperationException
操作在被处理的对象上执行。 ObjectDisposedException
操作不受支持(例如,在用于读取的流中重写 Stream.Write)。 NotSupportedException
转换将导致溢出(例如,显式强制转换运算符重载)。 OverflowException

对于所有其他情况,请考虑创建一个从 Exception 派生的类型,并抛出它。

如何解决违规

要修复此规则的违规问题,请将引发的异常类型更改为一个特定类型,该特定类型不属于保留类型之一。

Example

// This code violates the rule.
throw new Exception();
throw new NullReferenceException();
throw new IndexOutOfRangeException();
// ...

// This code satisfies the rule.
throw new ArgumentException();
throw new ArgumentNullException();
throw new InvalidOperationException();
// ...

// A minimal implementation of inheritance from Exception
public class CustomException : Exception { }

// Or create your own type that derives from Exception
// This code satisfies the rule too.
throw new CustomException();

何时禁止显示警告

不要抑制此规则发出的警告。