ArgumentException is thrown when a method is invoked and at least one of the passed arguments does not meet the parameter specification of the called method. All instances of ArgumentException should carry a meaningful error message describing the invalid argument, as well as the expected range of values for the argument.

The primary derived classes of ArgumentException are ArgumentNullException and ArgumentOutOfRangeException. These derived classes should be used instead of ArgumentException, except in situations where neither of the derived classes is acceptable. For example, exceptions should be thrown by:

using System;
publicsealedclass App
{
staticvoid Main()
{
// ArgumentException is not thrown because 10 is an even number.
Console.WriteLine("10 divided by 2 is {0}", DivideByTwo(10));
try
{
// ArgumentException is thrown because 7 is not an even number.
Console.WriteLine("7 divided by 2 is {0}", DivideByTwo(7));
}
catch (ArgumentException)
{
// Show the user that 7 cannot be divided by 2.
Console.WriteLine("7 is not divided by 2 integrally.");
}
}
staticint DivideByTwo(int num)
{
// If num is an odd number, throw an ArgumentException. if ((num & 1) == 1)
thrownew ArgumentException("Number must be even", "num");
// num is even, return half of its value. return num / 2;
}
}
// This code produces the following output. // // 10 divided by 2 is 5 // 7 is not divided by 2 integrally.