MSDN Library

System.ArgumentOutOfRangeException Class

The exception that is thrown when an argument's value is outside the legal range of values as defined by the overloaded member.

System . ArgumentOutOfRangeException

Namespace: System

Assembly: mscorlib (in mscorlib.dll)

Syntax

[SerializableAttribute]
public class ArgumentOutOfRangeException : ArgumentException

Remarks

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.

Constructors

Properties

Example

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}");
}