Instantiate argument exceptions correctly
Instantiate argument exceptions correctly
Microsoft docsDescription
Instead of calling the default constructor, call one of the constructor overloads that allows a more meaningful exception message to be provided. The exception message should target the developer and clearly explain the error condition and how to correct or avoid the exception.
The signatures of the one and two string constructors of System.ArgumentException and its derived types are not consistent with respect to the position message and paramName parameters. Make sure these constructors are called with the correct string arguments. The signatures are as follows:
ArgumentException(string message))ArgumentException(string message, string paramName))ArgumentNullException(string paramName))ArgumentNullException(string paramName, string message))ArgumentOutOfRangeException(string paramName))ArgumentOutOfRangeException(string paramName, string message))DuplicateWaitObjectException(string parameterName))DuplicateWaitObjectException(string parameterName, string message))
Cause
When a method has a parameter, and it throws an exception type that is, or derives from, System.ArgumentException, it is expected to call a constructor accepting a paramName parameter correctly. Possible causes include the following situations:
- A call is made to the default (parameterless) constructor of an exception type that is, or derives from, System.ArgumentException that also has a constructor that accepts a
paramNameparameter. - An incorrect string argument is passed to a parameterized constructor of an exception type that is, or derives from, System.ArgumentException. For example, the
paramNameargument doesn't match the name of one of the method's parameters. - A parameter name is passed for the
messageargument of the constructor of an exception type that is, or derives from, System.ArgumentException.
How to fix violations
To fix a violation of this rule, call a constructor that takes a message, a parameter name, or both, and make sure the arguments are proper for the type of System.ArgumentException being called. A code fix is available in Visual Studio for incorrectly positioned parameter names. To use it, position the cursor on the warning row and press <kbd>Ctrl</kbd>+<kbd>.</kbd> (period). Choose Swap the arguments order from the list of options that's presented. !Code fix for CA2208 - swap arguments. If a parameter name instead of a message is passed to the System.ArgumentException.%23ctor(System.String) method, the fixer provides the option to switch to the two-argument constructor instead. !Code fix for CA2208 - switch to two-argument constructor.
Example
#pragma warning disable CA2208
// The code that's violating the rule is on this line.
#pragma warning restore CA2208When to suppress
It's safe to suppress a warning from this rule only if a parameterized constructor is called with the correct string arguments.