ArgumentOutOfRangeException Class

 

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

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

System.Object
  System.Exception
    System.SystemException
      System.ArgumentException
        System.ArgumentOutOfRangeException

<SerializableAttribute>
<ComVisibleAttribute(True)>
Public Class ArgumentOutOfRangeException
	Inherits ArgumentException
	Implements ISerializable

NameDescription
System_CAPS_pubmethodArgumentOutOfRangeException()

Initializes a new instance of the ArgumentOutOfRangeException class.

System_CAPS_protmethodArgumentOutOfRangeException(SerializationInfo, StreamingContext)

Initializes a new instance of the ArgumentOutOfRangeException class with serialized data.

System_CAPS_pubmethodArgumentOutOfRangeException(String)

Initializes a new instance of the ArgumentOutOfRangeException class with the name of the parameter that causes this exception.

System_CAPS_pubmethodArgumentOutOfRangeException(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.

System_CAPS_pubmethodArgumentOutOfRangeException(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.

System_CAPS_pubmethodArgumentOutOfRangeException(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.

NameDescription
System_CAPS_pubpropertyActualValue

Gets the argument value that causes this exception.

System_CAPS_pubpropertyData

Gets a collection of key/value pairs that provide additional user-defined information about the exception.(Inherited from Exception.)

System_CAPS_pubpropertyHelpLink

Gets or sets a link to the help file associated with this exception.(Inherited from Exception.)

System_CAPS_pubpropertyHResult

Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.(Inherited from Exception.)

System_CAPS_pubpropertyInnerException

Gets the Exception instance that caused the current exception.(Inherited from Exception.)

System_CAPS_pubpropertyMessage

Gets the error message and the string representation of the invalid argument value, or only the error message if the argument value is null.(Overrides ArgumentException.Message.)

System_CAPS_pubpropertyParamName

Gets the name of the parameter that causes this exception.(Inherited from ArgumentException.)

System_CAPS_pubpropertySource

Gets or sets the name of the application or the object that causes the error.(Inherited from Exception.)

System_CAPS_pubpropertyStackTrace

Gets a string representation of the immediate frames on the call stack.(Inherited from Exception.)

System_CAPS_pubpropertyTargetSite

Gets the method that throws the current exception.(Inherited from Exception.)

NameDescription
System_CAPS_pubmethodEquals(Object)

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_protmethodFinalize()

Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)

System_CAPS_pubmethodGetBaseException()

When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.(Inherited from Exception.)

System_CAPS_pubmethodGetHashCode()

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethodGetObjectData(SerializationInfo, StreamingContext)

Sets the SerializationInfo object with the invalid argument value and additional exception information.(Overrides ArgumentException.GetObjectData(SerializationInfo, StreamingContext).)

System_CAPS_pubmethodGetType()

Gets the runtime type of the current instance.(Inherited from Exception.)

System_CAPS_protmethodMemberwiseClone()

Creates a shallow copy of the current Object.(Inherited from Object.)

System_CAPS_pubmethodToString()

Creates and returns a string representation of the current exception.(Inherited from Exception.)

NameDescription
System_CAPS_proteventSerializeObjectState

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

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:

You are retrieving the member of a collection by its index number, and the index number is invalid.

This is the most common cause of an ArgumentOutOfRangeException exception. Typically, the index number is invalid for one of three reasons:

  • The collection has no members, and your code assumes that it does. The following example attempts to retrieve the first element of a collection that has no elements:

    Imports System.Collections.Generic
    
    Module Example
       Public Sub Main()
          Dim list As New List(Of String)
          Console.WriteLine("Number of items: {0}", list.Count)
          Try
             Console.WriteLine("The first item: '{0}'", list(0))
          Catch e As ArgumentOutOfRangeException
             Console.WriteLine(e.Message)
          End Try
       End Sub
    End Module
    ' The example displays the following output:
    '   Number of items: 0
    '   Index was out of range. Must be non-negative and less than the size of the collection.
    '   Parameter name: index
    

    To prevent the exception, check whether the collection's Count property is greater than zero before attempting to retrieve any members, as the following code fragment does.

    If list.Count > 0 Then
       Console.WriteLine("The first item: '{0}'", list(0))
    End If
    

    In some cases, this may occur because you are attempting to add a member to a collection by using an index that does not exist, rather than by calling the method, such as Add, that exists for this purpose. The following example attempts to add an element to a collection by using a non-existent index rather than calling the List(Of T).Add method.

    Imports System.Collections.Generic
    
    Module Example
       Public Sub Main()
          Dim numbers As New List(Of Integer)
          numbers.AddRange( { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20 } )
    
          Dim squares As New List(Of Integer)
          For ctr As Integer = 0 To numbers.Count - 1
             squares(ctr) = CInt(numbers(ctr) ^ 2) 
          Next
       End Sub
    End Module
    ' The example displays the following output:
    '    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()
    

    The following code fragment corrects this error:

    Dim squares As New List(Of Integer)
    For ctr As Integer = 0 To numbers.Count - 1
       squares.Add(CInt(numbers(ctr) ^ 2)) 
    Next
    
  • You're attempting to retrieve an item whose index is negative. This usually occurs because you've searched a collection for the index of a particular element and have erroneously assumed that the search is successful. In the following example, the call to the List(Of T).FindIndex(Predicate(Of T)) method fails to find a string equal to "Z" and so returns -1. However, this is an invalid index value.

    Imports System.Collections.Generic
    
    Module Example
       Public Sub Main()
          Dim list As New List(Of String) 
          list.AddRange( { "A", "B", "C" } )
          ' Get the index of the element whose value is "Z".
          Dim index As Integer = list.FindIndex(AddressOf (New StringSearcher("Z")).FindEquals)
          Try
             Console.WriteLine("Index {0} contains '{1}'", index, list(index)) 
          Catch e As ArgumentOutOfRangeException
             Console.WriteLine(e.Message)
          End Try
       End Sub
    End Module
    
    Friend Class StringSearcher
       Dim value As String
    
       Public Sub New(value As String)
          Me.value = value
       End Sub
    
       Public Function FindEquals(s As String) As Boolean
          Return s.Equals(value, StringComparison.InvariantCulture) 
       End Function
    End Class
    ' The example displays the following output:
    '   Index was out of range. Must be non-negative and less than the size of the collection.
    '   Parameter name: index
    

    To prevent the exception, check that the search is successful by making sure that the returned index is greater than or equal to zero before attempting to retrieve the item from the collection, as the following code fragment does.

    ' Get the index of the element whose value is "Z".
    Dim index As Integer = list.FindIndex(AddressOf (New StringSearcher("Z")).FindEquals)
    If index >= 0 Then
       Console.WriteLine("Index {0} contains '{1}'", index, list(index)) 
    End If
    
  • You're attempting to retrieve an element whose index is equal to the value of the collection's Count property, as the following example illustrates.

    Imports System.Collections.Generic
    
    Module Example
       Public Sub Main()
          Dim list As New List(Of String) 
          list.AddRange( { "A", "B", "C" } )
          Try
             ' Display the elements in the list by index.
             For ctr As Integer = 0 To list.Count 
                Console.WriteLine("Index {0}: {1}", ctr, list(ctr)) 
             Next   
          Catch e As ArgumentOutOfRangeException
             Console.WriteLine(e.Message)
          End Try
       End Sub
    End Module
    ' The example displays the following output:
    '   Index 0: A
    '   Index 1: B
    '   Index 2: C
    '   Index was out of range. Must be non-negative and less than the size of the collection.
    '   Parameter name: index
    

    Because collections in the .NET Framework use zero-based indexing, the first element of the collection is at index 0, and the last element is at index Count - 1. You can eliminate the error by ensuring that you access the last element at index Count - 1, as the following code does.

    ' Display the elements in the list by index.
    For ctr As Integer = 0 To list.Count - 1 
       Console.WriteLine("Index {0}: {1}", ctr, list(ctr)) 
    Next   
    
You are attempting to perform a string operation by calling a string manipulation method, and the starting index does not exist in the string.

Overloads of methods such as such as String.Compare, String.CompareOrdinal, String.IndexOf, IndexOfAny, String.Insert, String.LastIndexOf, String.LastIndexOfAny, Remove, or String.Substring that allow you to specify the starting index of the operation require that the index be a valid position within the string. Valid indexes range from 0 to String.Length - 1.

There are four common causes of this ArgumentOutOfRangeException exception:

  • You are working with an empty string., or String.Empty. Because its String.Length property returns 0, any attempt to manipulate it by index throws an ArgumentOutOfRangeException exception. The following example, defines a GetFirstCharacter method that returns the first character of a string. If the string is empty, as the final string passed to the method is, the method throws an ArgumentOutOfRangeException exception.

    Module Example
       Public Sub Main()
           Dim words() As String = { "the", "today", "tomorrow", " ", "" }
           For Each word In words
              Console.WriteLine("First character of '{0}': '{1}'", 
                                word, GetFirstCharacter(word))
           Next                     
       End Sub
    
       Private Function GetFirstCharacter(s As String) As Char
          Return s(0)
       End Function
    End Module
    ' The example displays the following output:
    '    First character of 'the': 't'
    '    First character of 'today': 't'
    '    First character of 'tomorrow': 't'
    '    First character of ' ': ' '
    '    
    '    Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
    '       at Example.Main()
    

    You can eliminate the exception by testing whether the string's String.Length is greater than zero or by calling the IsNullOrEmpty method to ensure that the string is not null or empty. The following code fragment does the latter. In this case, if the string is null or empty, the GetFirstCharacter method returns U+0000.

    Function GetFirstCharacter(s As String) As Char
       If String.IsNullOrEmpty(s) Then 
          Return ChrW(0)
       Else   
          Return s(0)
       End If   
    End Function
    
  • You're manipulating a string based on the position of a substring within that string, and you've failed to determine whether the substring was actually found.

    The following example extracts the second word of a two-word phrase. It throws an ArgumentOutOfRangeException exception if the phrase consists of only one word, and therefore does not contain an embedded space character. This occurs because the call to the String.IndexOf(String) method returns -1 to indicate that the search failed, and this invalid value is then passed to the String.Substring(Int32) method.

    Module Example
       Public Sub Main()
          Dim phrases() As String = { "ocean blue", "concerned citizen", 
                                      "runOnPhrase" }
          For Each phrase In phrases
             Console.WriteLine("Second word is {0}", GetSecondWord(phrase))
          Next                            
      End Sub
    
      Function GetSecondWord(s As String) As String
         Dim pos As Integer = s.IndexOf(" ")
         Return s.Substring(pos).Trim()
      End Function
    End Module
    ' The example displays the following output:
    '       Second word is blue
    '       Second word is citizen
    '       
    '       Unhandled Exception: System.ArgumentOutOfRangeException: StartIndex cannot be less than zero.
    '       Parameter name: startIndex
    '          at System.String.Substring(Int32 startIndex, Int32 length)
    '          at Example.GetSecondWord(String s)
    '          at Example.Main()
    

    To eliminate the exception, validate the value returned by the string search method before calling the string manipulation method.

    Module Example
       Public Sub Main()
          Dim phrases() As String = { "ocean blue", "concerned citizen", 
                                      "runOnPhrase" }
          For Each phrase In phrases
             Dim word As String = GetSecondWord(phrase)
             If Not String.IsNullOrEmpty(word) Then _
                Console.WriteLine("Second word is {0}", word)
          Next                            
       End Sub
    
       Function GetSecondWord(s As String) As String
          Dim pos As Integer = s.IndexOf(" ")
          If pos >= 0
              Return s.Substring(pos).Trim()
          Else
             Return String.Empty
          End If
      End Function
    End Module
    ' The example displays the following output:
    '       Second word is blue
    '       Second word is citizen
    
You've attempted to extract a substring that is outside the range of the current string.

The methods that extract substrings all require that you specify the starting position of the substring and, for substrings that do not continue to the end of the string, the number of characters in the substring. Note that this is not the index of the last character in the substring.

An ArgumentOutOfRangeException exception is typically thrown in this case because you've incorrectly calculated the number of characters in the substring. If you are using a search method like String.IndexOf to identify the starting and ending positions of a substring:

  • If the character in the ending position returned by String.IndexOf is to be included in the substring, the ending position of the substring is given by the formula

    endIndex - startIndex + 1
    
  • If the character in the ending position returned by String.IndexOf is to be excluded from the substring, the ending position of the substring is given by the formula

    endIndex - startIndex 
    

The following example defines a FindWords method that uses the String.IndexOfAny(Char(), Int32) method to identify space characters and punctuation marks in a string and returns an array that contains the words found in the string.

Imports System.Collections.Generic

Module Example
   Public Sub Main()
      Dim sentence As String = "This is a simple, short sentence."
      Console.WriteLine("Words in '{0}':", sentence)
      For Each word In FindWords(sentence)
         Console.WriteLine("   '{0}'", word)
      Next
   End Sub

   Function FindWords(s As String) As String()
      Dim start, ending As Integer
      Dim delimiters() As Char = { " "c, "."c, ","c, ";"c, ":"c,
                                   "("c, ")"c }
      Dim words As New List(Of String)()

      Do While ending >= 0
         ending = s.IndexOfAny(delimiters, start)
         If ending >= 0
            If ending - start > 0 Then
               words.Add(s.Substring(start, ending - start)) 
            End If
            start = ending + 1
         Else
            If start < s.Length - 1 Then
               words.Add(s.Substring(start))
            End If      
         End If
      Loop    
      Return words.ToArray()                         
   End Function
End Module
' The example displays the following output:
'       Words in 'This is a simple, short sentence.':
'          'This'
'          'is'
'          'a'
'          'simple'
'          'short'
'          'sentence'
You have passed a negative number to a method with an argument that requires only positive numbers and zero, or you have passed either a negative number or zero to a method with an argument that requires only positive numbers.

For example, the Array.CreateInstance(Type, Int32, Int32, Int32) method requires that you specify the number of elements in each dimension of a two-dimensional array; valid values for each dimension can range from 0 to Int32.MaxValue. But because the dimension argument in the following example has a negative value, the method throws an ArgumentOutOfRangeException exception.

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.

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 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
A race condition exists in an app that is multithreaded or has tasks that execute asynchronously and that updates an array or collection.

The following example uses a List(Of T) object to populate a collection of Continent objects. It throws an ArgumentOutOfRangeException exception if the example attempts to display the seven items in the collection before the collection is fully populated.

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:

  • The continents collection. Its List(Of T).Add method is called from multiple threads. In addition, the main or primary thread assumes the collection is fully populated with seven elements when it iterates its members.

  • The msg string, which is concatenated from multiple threads.

To correct the error, ensure that shared state is accessed in a thread-safe way, as follows.

  • if your app uses an array or collection object, consider using a thread-safe collection class, such as the types in the System.Collections.Concurrent namespace or the System.Collections.Immutable out-of-band release.

  • Ensure that shared state (that is, resources that can be accessed by multiple threads) is accessed in a thread-safe way, so that only one thread at a time has exclusive access to the resources. A large number of classes, such as CountdownEvent, Interlocked, Monitor, and Mutex, are available to synchronize access to resources. For more information, see Managed Threading. In addition, language support is available through the lock statement in C# and the SyncLock construct in Visual Basic.

The following example addresses the ArgumentOutOfRangeException exception and the other issues from the previous example. It replaces the List(Of T) object with a ConcurrentBag(Of T) object to ensure that access to the collection is thread-safe, uses a CountdownEvent object to ensure that the application thread continues only after other threads have executed, and uses a lock to ensure that only one thread can access the msg variable at a time.

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.

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.

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

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Return to top
Show: