CA2201: Do not raise reserved exception types
TypeName |
DoNotRaiseReservedExceptionTypes |
CheckId |
CA2201 |
Category |
Microsoft.Usage |
Breaking Change |
Breaking |
Cause
A method raises an exception type that is too general or that is reserved by the runtime.
Rule Description
The following exception types are too general to provide sufficient information to the user:
The following exception types are reserved and should be thrown only by the common language runtime:
Do Not Throw General Exceptions
If you throw a general exception type, such as Exception or SystemException in a library or framework, it forces consumers to catch all exceptions, including unknown exceptions that they do not know how to handle.
Instead, either throw a more derived type that already exists in the framework, or create your own type that derives from Exception.
Throw Specific Exceptions
The following table shows parameters and which exceptions to throw when you validate the parameter, including the value parameter in the set accessor of a property:
Parameter Description |
Exception |
---|---|
null reference |
|
Outside the allowed range of values (such as an index for a collection or list) |
|
Invalid enum value |
|
Contains a format that does not meet the parameter specifications of a method (such as the format string for ToString(String)) |
|
Otherwise invalid |
When an operation is invalid for the current state of an object throw InvalidOperationException
When an operation is performed on an object that has been disposed throw ObjectDisposedException
When an operation is not supported (such as in an overridden Stream.Write in a Stream opened for reading) throw NotSupportedException
When a conversion would result in an overflow (such as in a explicit cast operator overload) throw OverflowException
For all other situations, consider creating your own type that derives from Exception and throw that.
How to Fix Violations
To fix a violation of this rule, change the type of the thrown exception to a specific type that is not one of the reserved types.
When to Suppress Warnings
Do not suppress a warning from this rule.