Rule Definition
The exception message should target the developer and clearly explain the error condition and how to correct or avoid the exception.The arguments fed to the ArgumentException or their constructors should be formed in a correct manner.
Following is the correct syntax and arguments of exceptions:
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)
Remediation
Make sure these constructors are called with the correct string arguments.
Violation Code Sample
public void Foo(Bar a, int[] b)
{
throw new ArgumentException(); // Noncompliant
throw new ArgumentException("My error message", "c"); // Noncompliant
throw new ArgumentException("My error message", "c", innerException); // Noncompliant
throw new ArgumentNullException("c"); // Noncompliant
throw new ArgumentNullException("My error message", "c"); // Noncompliant
throw new ArgumentOutOfRangeException("c");
throw new ArgumentOutOfRangeException("c", "My error message"); // Noncompliant
throw new ArgumentOutOfRangeException("c", b, "My error message"); // Noncompliant
throw new ArgumentNullException("All books must have a title.", nameof(title));
}
Fixed Code Sample
public void Foo(Bar a, Bar b)
{
throw new ArgumentException("My error message", "a");
throw new ArgumentException("My error message", "b", innerException);
throw new ArgumentNullException("a");
throw new ArgumentNullException(nameOf(a));
throw new ArgumentNullException("My error message", "a");
throw new ArgumentOutOfRangeException("b");
throw new ArgumentOutOfRangeException("b", "My error message");
throw new ArgumentOutOfRangeException("b", b, "My error message");
throw new ArgumentNullException(nameof(title), "All books must have a title.");
}
Reference
https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2208
https://cwe.mitre.org/data/definitions/397.html
https://cwe.mitre.org/data/definitions/687.html
Related Technologies
Technical Criterion
Programming Practices - Unexpected Behavior
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.