Instantiate argument exceptions correctly

TypeName

InstantiateArgumentExceptionsCorrectly

CheckId

CA2208

Category

Microsoft.Usage

Breaking Change

NonBreaking

Cause

A call is made to the default (parameterless) constructor of System.ArgumentException, System.ArgumentNullException, System.ArgumentOutOfRangeException, or System.DuplicateWaitObjectException, or one of their parameterized constructors is called with an incorrect string argument.

Rule Description

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 ArgumentException and its derived types are not consistent with respect to the 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)

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 ArgumentException being called.

When to Exclude Warnings

It is safe to exclude a warning from this rule only if a parameterized constructor is called with the correct string arguments.

Example

The following example shows a constructor that incorrectly instantiates an instance of the ArgumentNullException type.

The following example fixes the above violation by switching the constructor arguments.