Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.
Traducción
Inglés

Clase ArgumentOutOfRangeException

 

Publicado: octubre de 2016

Excepción que se produce cuando el valor de un argumento está fuera del intervalo de valores permitido definido por el método invocado.

Espacio de nombres:   System
Ensamblado:  mscorlib (en mscorlib.dll)

System::Object
  System::Exception
    System::SystemException
      System::ArgumentException
        System::ArgumentOutOfRangeException

[SerializableAttribute]
[ComVisibleAttribute(true)]
public ref class ArgumentOutOfRangeException : ArgumentException, 
	ISerializable

NombreDescripción
System_CAPS_pubmethodArgumentOutOfRangeException()

Inicializa una nueva instancia de la clase ArgumentOutOfRangeException.

System_CAPS_protmethodArgumentOutOfRangeException(SerializationInfo^, StreamingContext)

Inicializa una nueva instancia de la clase ArgumentOutOfRangeException con datos serializados.

System_CAPS_pubmethodArgumentOutOfRangeException(String^)

Inicializa una nueva instancia de la ArgumentOutOfRangeException clase con el nombre del parámetro que causa esta excepción.

System_CAPS_pubmethodArgumentOutOfRangeException(String^, Exception^)

Inicializa una nueva instancia de la ArgumentOutOfRangeException clase con un mensaje de error especificado y la excepción que es la causa de esta excepción.

System_CAPS_pubmethodArgumentOutOfRangeException(String^, Object^, String^)

Inicializa una nueva instancia de la ArgumentOutOfRangeException nombre de la clase con el parámetro, el valor del argumento y un mensaje de error especificado.

System_CAPS_pubmethodArgumentOutOfRangeException(String^, String^)

Inicializa una nueva instancia de la ArgumentOutOfRangeException clase con el nombre del parámetro que causa esta excepción y un mensaje de error especificado.

NombreDescripción
System_CAPS_pubpropertyActualValue

Obtiene el valor del argumento que causa esta excepción.

System_CAPS_pubpropertyData

Obtiene una colección de pares clave-valor que proporcionan más información definida por el usuario sobre la excepción.(Heredado de Exception).

System_CAPS_pubpropertyHelpLink

Obtiene o establece un vínculo al archivo de ayuda asociado a esta excepción.(Heredado de Exception).

System_CAPS_pubpropertyHResult

Obtiene o establece HRESULT, un valor numérico codificado que se asigna a una excepción específica.(Heredado de Exception).

System_CAPS_pubpropertyInnerException

Obtiene la instancia Exception que produjo la excepción actual.(Heredado de Exception).

System_CAPS_pubpropertyMessage

Obtiene el mensaje de error y la representación de cadena del valor de argumento no válido o el mensaje de error si el valor del argumento es null.(Invalida ArgumentException::Message).

System_CAPS_pubpropertyParamName

Obtiene el nombre del parámetro que causa esta excepción.(Heredado de ArgumentException).

System_CAPS_pubpropertySource

Devuelve o establece el nombre de la aplicación o del objeto que generó el error.(Heredado de Exception).

System_CAPS_pubpropertyStackTrace

Obtiene una representación de cadena de los marcos inmediatos en la pila de llamadas.(Heredado de Exception).

System_CAPS_pubpropertyTargetSite

Obtiene el método que produjo la excepción actual.(Heredado de Exception).

NombreDescripción
System_CAPS_pubmethodEquals(Object^)

Determina si el objeto especificado es igual al objeto actual.(Heredado de Object).

System_CAPS_protmethodFinalize()

Permite que un objeto intente liberar recursos y realizar otras operaciones de limpieza antes de ser reclamado por el recolector de basura. (Heredado de Object).

System_CAPS_pubmethodGetBaseException()

Cuando se invalida en una clase derivada, devuelve la clase Exception que representa la causa principal de una o más excepciones posteriores.(Heredado de Exception).

System_CAPS_pubmethodGetHashCode()

Sirve como la función hash predeterminada.(Heredado de Object).

System_CAPS_pubmethodGetObjectData(SerializationInfo^, StreamingContext)

Establece la SerializationInfo objeto con el valor de argumento no válido y la información adicional de la excepción.(Invalida ArgumentException::GetObjectData(SerializationInfo^, StreamingContext)).

System_CAPS_pubmethodGetType()

Obtiene el tipo en tiempo de ejecución de la instancia actual.(Heredado de Exception).

System_CAPS_protmethodMemberwiseClone()

Crea una copia superficial del Object actual.(Heredado de Object).

System_CAPS_pubmethodToString()

Crea y devuelve una representación de cadena de la excepción actual.(Heredado de Exception).

NombreDescripción
System_CAPS_proteventSerializeObjectState

Ocurre cuando una excepción se serializa para crear un objeto de estado de excepción que contenga datos serializados sobre la excepción.(Heredado de Exception).

An T:System.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 P:System.ArgumentException.ParamName property identifies the invalid argument, and the P:System.ArgumentOutOfRangeException.ActualValue property, if a value is present, identifies the invalid value.

Typically, an T:System.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:

  • Classes in the N:System.Collections and N:System.IO namespaces.

  • The T:System.Array class.

  • String manipulation methods in the T:System.String class.

The conditions in which an T:System.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 T:System.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:

    No hay ningún ejemplo de código disponible o este idioma no es compatible.

    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.

    No hay ningún ejemplo de código disponible o este idioma no es compatible.

    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 M:System.Collections.Generic.List`1.Add(`0) method.

    No hay ningún ejemplo de código disponible o este idioma no es compatible.

    The following code fragment corrects this error:

    No hay ningún ejemplo de código disponible o este idioma no es compatible.
  • 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 M:System.Collections.Generic.List`1.FindIndex(System.Predicate{`0}) method fails to find a string equal to "Z" and so returns -1. However, this is an invalid index value.

    No hay ningún ejemplo de código disponible o este idioma no es compatible.

    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.

    No hay ningún ejemplo de código disponible o este idioma no es compatible.
  • 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.

    No hay ningún ejemplo de código disponible o este idioma no es compatible.

    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.

    No hay ningún ejemplo de código disponible o este idioma no es compatible.
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 M:System.String.Compare(System.String,System.String), M:System.String.CompareOrdinal(System.String,System.Int32,System.String,System.Int32,System.Int32), M:System.String.IndexOf(System.String), M:System.String.IndexOfAny(System.Char[]), M:System.String.Insert(System.Int32,System.String), M:System.String.LastIndexOf(System.String), M:System.String.LastIndexOfAny(System.Char[]), M:System.String.Remove(System.Int32), or M:System.String.Substring(System.Int32) 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 P:System.String.Length - 1.

There are four common causes of this T:System.ArgumentOutOfRangeException exception:

  • You are working with an empty string., or F:System.String.Empty. Because its P:System.String.Length property returns 0, any attempt to manipulate it by index throws an T:System.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 T:System.ArgumentOutOfRangeException exception.

    No hay ningún ejemplo de código disponible o este idioma no es compatible.

    You can eliminate the exception by testing whether the string's P:System.String.Length is greater than zero or by calling the M:System.String.IsNullOrEmpty(System.String) 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.

    No hay ningún ejemplo de código disponible o este idioma no es compatible.
  • 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 T:System.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 M:System.String.IndexOf(System.String) method returns -1 to indicate that the search failed, and this invalid value is then passed to the M:System.String.Substring(System.Int32) method.

    No hay ningún ejemplo de código disponible o este idioma no es compatible.

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

    No hay ningún ejemplo de código disponible o este idioma no es compatible.
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 T:System.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 M:System.String.IndexOf(System.Char) to identify the starting and ending positions of a substring:

  • If the character in the ending position returned by M:System.String.IndexOf(System.Char) 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 M:System.String.IndexOf(System.Char) 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 M:System.String.IndexOfAny(System.Char[],System.Int32) method to identify space characters and punctuation marks in a string and returns an array that contains the words found in the string.

No hay ningún ejemplo de código disponible o este idioma no es compatible.
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 M:System.Array.CreateInstance(System.Type,System.Int32,System.Int32,System.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 F:System.Int32.MaxValue. But because the dimension argument in the following example has a negative value, the method throws an T:System.ArgumentOutOfRangeException exception.

No hay ningún ejemplo de código disponible o este idioma no es compatible.

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.

No hay ningún ejemplo de código disponible o este idioma no es compatible.

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.

No hay ningún ejemplo de código disponible o este idioma no es compatible.
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 T:System.Collections.Generic.List`1 object to populate a collection of Continent objects. It throws an T:System.ArgumentOutOfRangeException exception if the example attempts to display the seven items in the collection before the collection is fully populated.

No hay ningún ejemplo de código disponible o este idioma no es compatible.

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

  • The continents collection. Its M:System.Collections.Generic.List`1.Add(`0) 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 N: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 T:System.Threading.CountdownEvent, T:System.Threading.Interlocked, T:System.Threading.Monitor, and T:System.Threading.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 T:System.ArgumentOutOfRangeException exception and the other issues from the previous example. It replaces the T:System.Collections.Generic.List`1 object with a T:System.Collections.Concurrent.ConcurrentBag`1 object to ensure that access to the collection is thread-safe, uses a T:System.Threading.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.

No hay ningún ejemplo de código disponible o este idioma no es compatible.

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

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

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

No hay ningún ejemplo de código disponible o este idioma no es compatible.

Plataforma universal de Windows
Disponible desde 8
.NET Framework
Disponible desde 1.1
Biblioteca de clases portable
Se admite en: plataformas portátiles de .NET
Silverlight
Disponible desde 2.0
Windows Phone Silverlight
Disponible desde 7.0
Windows Phone
Disponible desde 8.1

Cualquier miembro ( Compartido en Visual Basic) estático público de este tipo es seguro para subprocesos. No se garantiza que los miembros de instancia sean seguros para subprocesos.

Volver al principio
Mostrar: