| 属性 | 值 |
|---|---|
| 规则 ID | CA2201 |
| 标题 | 不要引发保留的异常类型 |
| 类别 | 使用情况 |
| 修复是中断修复还是非中断修复 | 重大 |
| 在 .NET 9 中默认启用 | 否 |
原因
方法引发的异常类型太过笼统,或已由运行时保留。
规则说明
以下异常类型太过笼统,无法为用户提供足够的信息:
以下异常类型已保留,仅应由公共语言运行时引发:
- System.AccessViolationException
- System.ExecutionEngineException
- System.IndexOutOfRangeException
- System.NullReferenceException
- System.OutOfMemoryException
- System.Runtime.InteropServices.COMException
- System.Runtime.InteropServices.ExternalException
- System.Runtime.InteropServices.SEHException
- System.StackOverflowException
请勿引发一般异常
如果在库或框架中引发一般异常类型,如 Exception 或 SystemException,将强制使用者捕捉所有异常,包括不知该如何处理的未知异常。
相反,要么引发框架中已存在的派生程度更高的类型,要么创建自己从 Exception 派生的类型。
引发特定异常
下表显示了要为各种类型的无效参数引发的异常,包括属性的 set 访问器中的值参数。
| 参数无效 | 例外 |
|---|---|
null 参考 |
ArgumentNullException |
| 超出允许的值(如集合或列表的索引)范围 | ArgumentOutOfRangeException |
enum 值无效 |
InvalidEnumArgumentException |
包含不满足方法参数规范的格式(如适用于 ToString(String) 格式字符串) |
FormatException |
| 否则无效 | ArgumentException |
下表显示了要为各种类型的无效操作引发的异常。
| 操作无效 | 例外 |
|---|---|
| 操作对对象的当前状态无效。 | InvalidOperationException |
| 操作在已释放的对象上执行。 | ObjectDisposedException |
操作不受支持(例如,在因读取而打开的 Stream 中重写 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();
何时禁止显示警告
不禁止显示此规则发出的警告。