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 System.ArgumentNullException
Outside the allowed range of values (such as an index for a collection or list) System.ArgumentOutOfRangeException
Invalid enum value System.ComponentModel.InvalidEnumArgumentException
Contains a format that does not meet the parameter specifications of a method (such as the format string for ToString(String)) System.FormatException
Otherwise invalid System.ArgumentException

When an operation is invalid for the current state of an object throw System.InvalidOperationException

When an operation is performed on an object that has been disposed throw System.ObjectDisposedException

When an operation is not supported (such as in an overridden Stream.Write in a Stream opened for reading) throw System.NotSupportedException

When a conversion would result in an overflow (such as in a explicit cast operator overload) throw System.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.