ArgumentOutOfRangeException Class (System) (original) (raw)

Definition

The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.

public ref class ArgumentOutOfRangeException : ArgumentException
public class ArgumentOutOfRangeException : ArgumentException
[System.Serializable]
public class ArgumentOutOfRangeException : ArgumentException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class ArgumentOutOfRangeException : ArgumentException
type ArgumentOutOfRangeException = class
    inherit ArgumentException
type ArgumentOutOfRangeException = class
    inherit ArgumentException
    interface ISerializable
[<System.Serializable>]
type ArgumentOutOfRangeException = class
    inherit ArgumentException
    interface ISerializable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type ArgumentOutOfRangeException = class
    inherit ArgumentException
    interface ISerializable
Public Class ArgumentOutOfRangeException
Inherits ArgumentException

Inheritance

ArgumentOutOfRangeException

Inheritance

ArgumentOutOfRangeException

Attributes

Implements

Examples

The following example defines a class to contain information about an invited guest. If the guest is younger than 21, an ArgumentOutOfRangeException exception is thrown.

using System;
using static System.Console;

public class Program
{
    public static void Main(string[] args)
    {
        try
        {
            var guest1 = new Guest("Ben", "Miller", 17);
            WriteLine(guest1.GuestInfo);
        }
        catch (ArgumentOutOfRangeException argumentOutOfRangeException)
        {
            WriteLine($"Error: {argumentOutOfRangeException.Message}");
        }
    }
}

class Guest
{
    private const int minimumRequiredAge = 21;

    private string firstName;
    private string lastName;
    private int age;

    public Guest(string firstName, string lastName, int age)
    {
        if (age < minimumRequiredAge)
            throw new ArgumentOutOfRangeException(nameof(age), $"All guests must be {minimumRequiredAge}-years-old or older.");

        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public string GuestInfo => $"{firstName} {lastName}, {age}";
}
open System

type Guest(fName: string, lName: string, age: int) =
    let minimumRequiredAge = 21

    do if age < minimumRequiredAge then 
        raise (ArgumentOutOfRangeException(nameof age, $"All guests must be {minimumRequiredAge}-years-old or older."))

    member _.FirstName = fName
    member _.LastName = lName
    member _.GuestInfo() = $"{fName} {lName}, {age}"

try
    let guest1 = Guest("Ben", "Miller", 17);
    printfn $"{guest1.GuestInfo()}"
with
| :? ArgumentOutOfRangeException as e ->
    printfn $"Error: {e.Message}"
Module Module1
   Public Sub Main()
       Try
           Dim guest1 As Guest = New Guest("Ben", "Miller", 17)
           Console.WriteLine(guest1.GuestInfo)
       Catch outOfRange As ArgumentOutOfRangeException
           Console.WriteLine("Error: {0}", outOfRange.Message)
       End Try
   End Sub
End Module

Class Guest
    Private FirstName As String
    Private LastName As String
    Private Age As Integer

    Public Sub New(ByVal fName As String, ByVal lName As String, ByVal age As Integer)
        MyBase.New()
        FirstName = fName
        LastName = lName
        If (age < 21) Then
            Throw New ArgumentOutOfRangeException("age", "All guests must be 21-years-old or older.")
        Else
            age = age
        End If
    End Sub

    Public Function GuestInfo() As String
        Dim gInfo As String = (FirstName + (" " _
                    + (Me.LastName + (", " + Me.Age.ToString))))
        Return gInfo
    End Function
End Class

An ArgumentOutOfRangeException exception is thrown when a method is invoked and at least one of the arguments passed to the method is not null and contains an invalid value that is not a member of the set of values expected for the argument. The ParamName property identifies the invalid argument, and the ActualValue property, if a value is present, identifies the invalid value.

Typically, an ArgumentOutOfRangeException results from developer error. Instead of handling the exception in a try/catch block, you should eliminate the cause of the exception or, if the argument is returned by a method call or input by the user before being passed to the method that throws the exception, you should validate arguments before passing them to the method.

ArgumentOutOfRangeException is used extensively by:

The conditions in which an ArgumentOutOfRangeException exception is thrown include the following:

using System;  
public class Example01  
{  
    public static void Main()  
    {  
        int dimension1 = 10;  
        int dimension2 = -1;  
        try  
        {  
            Array arr = Array.CreateInstance(typeof(string),  
                                             dimension1, dimension2);  
        }  
        catch (ArgumentOutOfRangeException e)  
        {  
            if (e.ActualValue != null)  
                Console.WriteLine("{0} is an invalid value for {1}: ", e.ActualValue, e.ParamName);  
            Console.WriteLine(e.Message);  
        }  
    }  
}  
// The example displays the following output:  
//     Non-negative number required.  
//     Parameter name: length2  
open System  
let dimension1 = 10  
let dimension2 = -1  
try  
    let arr = Array.CreateInstance(typeof<string>, dimension1, dimension2)  
    printfn "%A" arr  
with  
| :? ArgumentOutOfRangeException as e ->  
    if not (isNull e.ActualValue) then  
        printfn $"{e.ActualValue} is an invalid value for {e.ParamName}: "  
    printfn $"{e.Message}"  
// The example displays the following output:  
//     Non-negative number required. (Parameter 'length2')  
Module Example  
   Public Sub Main()  
      Dim dimension1 As Integer = 10  
      Dim dimension2 As Integer = -1  
      Try  
         Dim arr AS Array = Array.CreateInstance(GetType(String),  
                                                 dimension1, dimension2)  
      Catch e As ArgumentOutOfRangeException  
         If e.ActualValue IsNot Nothing Then  
            Console.WriteLine("{0} is an invalid value for {1}: ",  
                              e.ActualValue, e.ParamName)  
         End If  
         Console.WriteLine(e.Message)  
      End Try  
   End Sub  
End Module  
' The example displays the following output:  
'     Non-negative number required.  
'     Parameter name: length2  

To correct the error, ensure that the value of the invalid argument is non-negative. You can do this by providing a valid value, as the following code fragment does.

int dimension1 = 10;  
int dimension2 = 10;  
Array arr = Array.CreateInstance(typeof(string),  
                                 dimension1, dimension2);  
let dimension1 = 10  
let dimension2 = 10  
let arr = Array.CreateInstance(typeof<string>, dimension1, dimension2)  
printfn "%A" arr  
Dim dimension1 As Integer = 10  
Dim dimension2 As Integer = 10  
Dim arr As Array = Array.CreateInstance(GetType(String),  
                                        dimension1, dimension2)  

You can also validate the input and, if it is invalid, take some action. The following code fragment displays an error message instead of calling the method.

if (dimension1 < 0 || dimension2 < 0)  
{  
    Console.WriteLine("Unable to create the array.");  
    Console.WriteLine("Specify non-negative values for the two dimensions.");  
}  
else  
{  
    arr = Array.CreateInstance(typeof(string),  
                               dimension1, dimension2);  
}  
if dimension1 < 0 || dimension2 < 0 then  
    printfn "Unable to create the array."  
    printfn "Specify non-negative values for the two dimensions."  
else  
    let arr = Array.CreateInstance(typeof<string>, dimension1, dimension2)  
    printfn "%A" arr  
If dimension1 < 0 OrElse dimension2 < 0 Then  
   Console.WriteLine("Unable to create the array.")  
   Console.WriteLine("Specify non-negative values for the two dimensions.")  
Else  
   arr = Array.CreateInstance(GetType(String),  
                              dimension1, dimension2)  
End If  
using System;  
using System.Collections.Generic;  
using System.Threading;  
public class Continent  
{  
   public string? Name { get; set; }  
   public int Population { get; set; }  
   public Decimal Area { get; set; }  
}  
public class Example11  
{  
   static List<Continent> continents = new List<Continent>();  
   static string? s_msg;  
   public static void Main()  
   {  
      String[] names = { "Africa", "Antarctica", "Asia",  
                         "Australia", "Europe", "North America",  
                         "South America" };  
      // Populate the list.  
      foreach (var name in names) {  
         var th = new Thread(PopulateContinents);  
         th.Start(name);  
      }  
      Console.WriteLine(s_msg);  
      Console.WriteLine();  
      // Display the list.  
      for (int ctr = 0; ctr < names.Length; ctr++) {  
         var continent = continents[ctr];  
         Console.WriteLine("{0}: Area: {1}, Population {2}",  
                           continent.Name, continent.Population,  
                           continent.Area);  
      }  
   }  
   private static void PopulateContinents(Object? obj)  
   {  
      string? name = obj?.ToString();  
      s_msg += string.Format("Adding '{0}' to the list.\n", name);  
      var continent = new Continent();  
      continent.Name = name;  
      // Sleep to simulate retrieving remaining data.  
      Thread.Sleep(50);  
      continents.Add(continent);  
   }  
}  
// The example displays output like the following:  
//    Adding //Africa// to the list.  
//    Adding //Antarctica// to the list.  
//    Adding //Asia// to the list.  
//    Adding //Australia// to the list.  
//    Adding //Europe// to the list.  
//    Adding //North America// to the list.  
//    Adding //South America// to the list.  
//  
//  
//  
//    Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.  
//    Parameter name: index  
//       at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)  
//       at Example.Main()  
open System.Threading  
type Continent =  
    { Name: string  
      Population: int  
      Area: decimal }  
let continents = ResizeArray<Continent>()  
let mutable msg = ""  
let names =  
    [ "Africa"; "Antarctica"; "Asia"  
      "Australia"; "Europe"; "North America"  
      "South America" ]  
let populateContinents obj =  
    let name = string obj  
    msg <- msg + $"Adding '{name}' to the list.\n"  
    // Sleep to simulate retrieving data.  
    Thread.Sleep 50  
    let continent =  
        { Name = name  
          Population = 0  
          Area = 0M }  
    continents.Add continent  
        
// Populate the list.  
for name in names do  
    let th = Thread(ParameterizedThreadStart populateContinents)  
    th.Start name  
        
printfn $"{msg}\n"  
// Display the list.  
for i = 0 to names.Length - 1 do  
    let continent = continents[i]  
    printfn $"{continent.Name}: Area: {continent.Population}, Population {continent.Area}"  
// The example displays output like the following:  
//    Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')  
//       at System.Collections.Generic.List`1.get_Item(Int32 index)  
//       at <StartupCode$argumentoutofrangeexception>.$Race1.main@()  
Imports System.Collections.Generic  
Imports System.Threading  
Public Class Continent  
   Public Property Name As String  
   Public Property Population As Integer  
   Public Property Area As Decimal  
End Class  
Module Example  
   Dim continents As New List(Of Continent)  
   Dim msg As String  
        
   Public Sub Main()  
      Dim names() As String = { "Africa", "Antarctica", "Asia",  
                                     "Australia", "Europe", "North America",  
                                     "South America" }  
      ' Populate the list.  
      For Each name In names  
         Dim th As New Thread(AddressOf PopulateContinents)  
         th.Start(name)  
      Next  
      Console.WriteLine(msg)  
      Console.WriteLine()  
      ' Display the list.  
      For ctr As Integer = 0 To names.Length - 1  
         Dim continent = continents(ctr)  
         Console.WriteLine("{0}: Area: {1}, Population {2}",  
                           continent.Name, continent.Population,  
                           continent.Area)  
      Next  
   End Sub  
     
   Private Sub PopulateContinents(obj As Object)  
      Dim name As String = obj.ToString()  
      msg += String.Format("Adding '{0}' to the list.{1}", name, vbCrLf)  
      Dim continent As New Continent()  
      continent.Name = name  
      ' Sleep to simulate retrieving remaining data.  
      Thread.Sleep(50)  
      continents.Add(continent)  
   End Sub  
End Module  
' The example displays output like the following:  
'    Adding 'Africa' to the list.  
'    Adding 'Antarctica' to the list.  
'    Adding 'Asia' to the list.  
'    Adding 'Australia' to the list.  
'    Adding 'Europe' to the list.  
'    Adding 'North America' to the list.  
'    Adding 'South America' to the list.  
'  
'  
'  
'    Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.  
'    Parameter name: index  
'       at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)  
'       at Example.Main()  

In this case, two resources are accessed from multiple threads:

using System;  
using System.Collections.Concurrent;  
using System.Threading;  
public class ContinentD  
{  
   public string? Name { get; set; }  
   public int Population { get; set; }  
   public Decimal Area { get; set; }  
}  
public class Example12  
{  
   static ConcurrentBag<ContinentD> ContinentDs = new ConcurrentBag<ContinentD>();  
   static CountdownEvent? gate;  
   static string msg = string.Empty;  
   public static void Main()  
   {  
      String[] names = { "Africa", "Antarctica", "Asia",  
                         "Australia", "Europe", "North America",  
                         "South America" };  
      gate = new CountdownEvent(names.Length);  
      // Populate the list.  
      foreach (var name in names) {  
         var th = new Thread(PopulateContinentDs);  
         th.Start(name);  
      }  
      // Display the list.  
      gate.Wait();  
      Console.WriteLine(msg);  
      Console.WriteLine();  
      var arr = ContinentDs.ToArray();  
      for (int ctr = 0; ctr < names.Length; ctr++) {  
         var ContinentD = arr[ctr];  
         Console.WriteLine("{0}: Area: {1}, Population {2}",  
                           ContinentD.Name, ContinentD.Population,  
                           ContinentD.Area);  
      }  
   }  
   private static void PopulateContinentDs(Object? obj)  
   {  
      string? name = obj?.ToString();  
      lock(msg) {  
         msg += string.Format("Adding '{0}' to the list.\n", name);  
      }  
      var ContinentD = new ContinentD();  
      ContinentD.Name = name;  
      // Sleep to simulate retrieving remaining data.  
      Thread.Sleep(25);  
      ContinentDs.Add(ContinentD);  
      gate?.Signal();  
   }  
}  
// The example displays output like the following:  
//       Adding 'Africa' to the list.  
//       Adding 'Antarctica' to the list.  
//       Adding 'Asia' to the list.  
//       Adding 'Australia' to the list.  
//       Adding 'Europe' to the list.  
//       Adding 'North America' to the list.  
//       Adding 'South America' to the list.  
//  
//  
//       Africa: Area: 0, Population 0  
//       Antarctica: Area: 0, Population 0  
//       Asia: Area: 0, Population 0  
//       Australia: Area: 0, Population 0  
//       Europe: Area: 0, Population 0  
//       North America: Area: 0, Population 0  
//       South America: Area: 0, Population 0  
open System.Collections.Concurrent  
open System.Threading  
type Continent =  
    { Name: string  
      Population: int  
      Area: decimal }  
let continents = ConcurrentBag<Continent>();  
let mutable msg = ""  
let names =  
    [ "Africa"; "Antarctica"; "Asia"  
      "Australia"; "Europe"; "North America"  
      "South America" ]  
let gate = new CountdownEvent(names.Length)  
let populateContinents obj =  
    let name = string obj  
    lock msg (fun () ->  
        msg <- msg + $"Adding '{name}' to the list.\n" )  
    // Sleep to simulate retrieving remaining data.  
    let continent =  
        { Name = name  
          Population = 0  
          Area = 0M }  
    Thread.Sleep 25  
    continents.Add continent  
    gate.Signal() |> ignore  
// Populate the list.  
for name in names do  
    let th = Thread(ParameterizedThreadStart populateContinents)  
    th.Start name  
// Display the list.  
gate.Wait();  
printfn $"{msg}\n"  
let arr = continents.ToArray();  
for i = 0 to names.Length - 1 do  
    let continent = arr[i]  
    printfn $"{continent.Name}: Area: {continent.Population}, Population {continent.Area}"  
// The example displays output like the following:  
//       Adding 'Africa' to the list.  
//       Adding 'Antarctica' to the list.  
//       Adding 'Asia' to the list.  
//       Adding 'Australia' to the list.  
//       Adding 'Europe' to the list.  
//       Adding 'North America' to the list.  
//       Adding 'South America' to the list.  
//  
//  
//       Africa: Area: 0, Population 0  
//       Antarctica: Area: 0, Population 0  
//       Asia: Area: 0, Population 0  
//       Australia: Area: 0, Population 0  
//       Europe: Area: 0, Population 0  
//       North America: Area: 0, Population 0  
//       South America: Area: 0, Population 0  
Imports System.Collections.Concurrent  
Imports System.Threading  
Public Class Continent  
   Public Property Name As String  
   Public Property Population As Integer  
   Public Property Area As Decimal  
End Class  
Module Example  
   Dim continents As New ConcurrentBag(Of Continent)  
   Dim gate As CountdownEvent  
   Dim msg As String = String.Empty  
        
   Public Sub Main()  
      Dim names() As String = { "Africa", "Antarctica", "Asia",  
                                "Australia", "Europe", "North America",  
                                "South America" }  
      gate = new CountdownEvent(names.Length)  
        
      ' Populate the list.  
      For Each name In names  
         Dim th As New Thread(AddressOf PopulateContinents)  
         th.Start(name)  
      Next  
      ' Display the list.  
      gate.Wait()  
      Console.WriteLine(msg)  
      Console.WriteLine()  
      For ctr As Integer = 0 To names.Length - 1  
         Dim continent = continents(ctr)  
         Console.WriteLine("{0}: Area: {1}, Population {2}",  
                           continent.Name, continent.Population,  
                           continent.Area)  
      Next  
   End Sub  
     
   Private Sub PopulateContinents(obj As Object)  
      Dim name As String = obj.ToString()  
      SyncLock msg  
         msg += String.Format("Adding '{0}' to the list.{1}", name, vbCrLf)  
      End SyncLock  
      Dim continent As New Continent()  
      continent.Name = name  
      ' Sleep to simulate retrieving remaining data.  
      Thread.Sleep(25)  
      continents.Add(continent)  
      gate.Signal()  
   End Sub  
End Module  
' The example displays output like the following:  
'    Adding 'Africa' to the list.  
'    Adding 'Antarctica' to the list.  
'    Adding 'Asia' to the list.  
'    Adding 'Australia' to the list.  
'    Adding 'Europe' to the list.  
'    Adding 'North America' to the list.  
'    Adding 'South America' to the list.  
'  
'  
'    Africa: Area: 0, Population 0  
'    Antarctica: Area: 0, Population 0  
'    Asia: Area: 0, Population 0  
'    Australia: Area: 0, Population 0  
'    Europe: Area: 0, Population 0  
'    North America: Area: 0, Population 0  
'    South America: Area: 0, Population 0  

ArgumentOutOfRangeException uses the HRESULT COR_E_ARGUMENTOUTOFRANGE, which has the value 0x80131502.

For a list of initial property values for an instance of ArgumentOutOfRangeException, see the ArgumentOutOfRangeException constructors.

Constructors

ArgumentOutOfRangeException() Initializes a new instance of the ArgumentOutOfRangeException class.
ArgumentOutOfRangeException(SerializationInfo, StreamingContext) Obsolete. Initializes a new instance of the ArgumentOutOfRangeException class with serialized data.
ArgumentOutOfRangeException(String, Exception) Initializes a new instance of the ArgumentOutOfRangeException class with a specified error message and the exception that is the cause of this exception.
ArgumentOutOfRangeException(String, Object, String) Initializes a new instance of the ArgumentOutOfRangeException class with the parameter name, the value of the argument, and a specified error message.
ArgumentOutOfRangeException(String, String) Initializes a new instance of the ArgumentOutOfRangeException class with the name of the parameter that causes this exception and a specified error message.
ArgumentOutOfRangeException(String) Initializes a new instance of the ArgumentOutOfRangeException class with the name of the parameter that causes this exception.

Properties

ActualValue Gets the argument value that causes this exception.
Data Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception)
HelpLink Gets or sets a link to the help file associated with this exception. (Inherited from Exception)
HResult Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception)
InnerException Gets the Exception instance that caused the current exception. (Inherited from Exception)
Message Gets the error message and the string representation of the invalid argument value, or only the error message if the argument value is null.
ParamName Gets the name of the parameter that causes this exception. (Inherited from ArgumentException)
Source Gets or sets the name of the application or the object that causes the error. (Inherited from Exception)
StackTrace Gets a string representation of the immediate frames on the call stack. (Inherited from Exception)
TargetSite Gets the method that throws the current exception. (Inherited from Exception)

Methods

Equals(Object) Determines whether the specified object is equal to the current object. (Inherited from Object)
GetBaseException() When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception)
GetHashCode() Serves as the default hash function. (Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext) Obsolete. Sets the SerializationInfo object with the invalid argument value and additional exception information.
GetType() Gets the runtime type of the current instance. (Inherited from Exception)
MemberwiseClone() Creates a shallow copy of the current Object. (Inherited from Object)
ThrowIfEqual(T, T, String) Throws an ArgumentOutOfRangeException if value is equal to other.
ThrowIfGreaterThan(T, T, String) Throws an ArgumentOutOfRangeException if value is greater than other.
ThrowIfGreaterThanOrEqual(T, T, String) Throws an ArgumentOutOfRangeException if value is greater than or equal to other.
ThrowIfLessThan(T, T, String) Throws an ArgumentOutOfRangeException if value is less than other.
ThrowIfLessThanOrEqual(T, T, String) Throws an ArgumentOutOfRangeException if value is less than or equal to other.
ThrowIfNegative(T, String) Throws an ArgumentOutOfRangeException if value is negative.
ThrowIfNegativeOrZero(T, String) Throws an ArgumentOutOfRangeException if value is negative or zero.
ThrowIfNotEqual(T, T, String) Throws an ArgumentOutOfRangeException if value is not equal to other.
ThrowIfZero(T, String) Throws an ArgumentOutOfRangeException if value is zero.
ToString() Creates and returns a string representation of the current exception. (Inherited from Exception)

Events

SerializeObjectState Obsolete. Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception)

Applies to

See also