CA2208: Instantiate argument exceptions correctly
TypeName | InstantiateArgumentExceptionsCorrectly |
CheckId | CA2208 |
Category | Microsoft.Usage |
Breaking Change | Non Breaking |
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].
-
An incorrect string argument is passed to a parameterized constructor of an exception type that is, or derives from [System.ArgumentException.]
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)
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.
The following example shows a constructor that incorrectly instantiates an instance of the ArgumentNullException type.
using System; namespace Samples1 { public class Book { private readonly string _Title; public Book(string title) { // Violates this rule (constructor arguments are switched) if (title == null) throw new ArgumentNullException("title cannot be a null reference (Nothing in Visual Basic)", "title"); _Title = title; } public string Title { get { return _Title; } } } }
The following example fixes the above violation by switching the constructor arguments.
namespace Samples2 { public class Book { private readonly string _Title; public Book(string title) { if (title == null) throw new ArgumentNullException("title", "title cannot be a null reference (Nothing in Visual Basic)"); _Title = title; } public string Title { get { return _Title; } } } }
- 8/12/2010
- Simon4