The exception that is thrown when an argument's value is outside the legal range of values as defined by the overloaded member.
Namespace: System
Assembly: mscorlib (in mscorlib.dll)
[SerializableAttribute]
public class ArgumentOutOfRangeException : ArgumentException
An ArgumentOutOfRangeException indicates that a method parameter has been assigned a value that is not valid. For example, if a method expects a parameter to be between 0 and 100 (inclusive), and it is called with a value of -5 or 105, an ArgumentOutOfRangeException is thrown.
The ArgumentOutOfRangeException class inherits from the ArgumentException class. The ArgumentException class is the base class for exceptions that are thrown when a method is passed an invalid argument.
The ActualValue property contains the value that caused the exception. The ParamName property contains the name of the parameter that caused the exception.
ArgumentOutOfRangeException class.
ArgumentOutOfRangeException class with the name of the parameter that causes this exception.
ArgumentOutOfRangeException class with a specified error message and the name of the parameter that causes this exception.
ArgumentOutOfRangeException class with a specified error message, the name of the parameter that causes this exception, and the value of the parameter that causes this exception.
ArgumentOutOfRangeException class with serialized data.
The following code example demonstrates how to throw an ArgumentOutOfRangeException.
public void SetAge(int age)
{
if (age < 0 || age > 120)
{
throw new ArgumentOutOfRangeException(nameof(age), "Age must be between 0 and 120.");
}
this.age = age;
}
// Usage:
try
{
myObject.SetAge(-5);
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine($"Parameter: {ex.ParamName}");
Console.WriteLine($"Actual Value: {ex.ActualValue}");
}