ArgumentOutOfRangeException Class

Definición

Excepción que se produce cuando el valor de un argumento está fuera del intervalo de valores permitido definido por el método invocado. The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.

[System.Runtime.InteropServices.ComVisible(true)]
public class ArgumentOutOfRangeException : ArgumentException
Herencia
Atributos

Ejemplos

El ejemplo siguiente define una clase que contenga información sobre un invitado.The following example defines a class to contain information about an invited guest. Si el invitado tiene menos de 21, un ArgumentOutOfRangeException es una excepción.If the guest is younger than 21, an ArgumentOutOfRangeException exception is thrown.

using System;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            Guest guest1 = new Guest("Ben", "Miller", 17);
            Console.WriteLine(guest1.GuestInfo());
        }
        catch (ArgumentOutOfRangeException outOfRange)
        {

            Console.WriteLine("Error: {0}", outOfRange.Message);
        }
    }
}

class Guest
{
    private string FirstName;
    private string LastName;
    private int Age;

    public Guest(string fName, string lName, int age)
    {
        FirstName = fName;
        LastName = lName;
        if (age < 21)
            throw new ArgumentOutOfRangeException("age","All guests must be 21-years-old or older.");
        else
            Age = age;
    }

    public string GuestInfo()
    {
        string gInfo = FirstName + " " + LastName + ", " + Age.ToString();
        return(gInfo);
    }
}
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

Comentarios

Un ArgumentOutOfRangeException excepción se produce cuando se invoca un método y al menos uno de los argumentos pasados al método no es null y contiene un valor no válido que no sea miembro del conjunto de valores esperados para el argumento.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. El ParamName propiedad identifica el argumento no válido y el ActualValue propiedad, si está presente, un valor que identifica el valor no válido.The ParamName property identifies the invalid argument, and the ActualValue property, if a value is present, identifies the invalid value.

Normalmente, un ArgumentOutOfRangeException da como resultado de error de desarrollador.Typically, an ArgumentOutOfRangeException results from developer error. En lugar de controlar la excepción en un try / catch bloque, debe eliminar la causa de la excepción o, si el argumento es devuelto por una llamada al método o escrito por el usuario antes de que se pasa al método que produce la excepción , debe validar argumentos antes de pasarlas al método.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 es utilizada por:ArgumentOutOfRangeException is used extensively by:

Las condiciones en las que un ArgumentOutOfRangeException excepción incluyen lo siguiente:The conditions in which an ArgumentOutOfRangeException exception is thrown include the following:

Va a recuperar al miembro de una colección por su número de índice y el número de índice no es válido.You are retrieving the member of a collection by its index number, and the index number is invalid.
Esta es la causa más común de un ArgumentOutOfRangeException excepción.This is the most common cause of an ArgumentOutOfRangeException exception. Normalmente, el número de índice es válido para uno de estos tres motivos:Typically, the index number is invalid for one of three reasons:

  • La colección no tiene ningún miembro, y el código se da por supuesto que sí lo haga.The collection has no members, and your code assumes that it does. El ejemplo siguiente se intenta recuperar el primer elemento de una colección que no tiene elementos:The following example attempts to retrieve the first element of a collection that has no elements:

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main()
       {
          var list = new List<String>();
          Console.WriteLine("Number of items: {0}", list.Count);
          try {
             Console.WriteLine("The first item: '{0}'", list[0]);
          }
          catch (ArgumentOutOfRangeException e) {
             Console.WriteLine(e.Message);
          }
       }
    }
    // 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
    
    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
    

    Para evitar la excepción, compruebe si la colección Count propiedad es mayor que cero antes de intentar recuperar los miembros, como hace el siguiente fragmento de código.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)
       Console.WriteLine("The first item: '{0}'", list[0]);
    
    If list.Count > 0 Then
       Console.WriteLine("The first item: '{0}'", list(0))
    End If
    

    En algunos casos, esto puede ocurrir porque está intentando agregar un miembro a una colección mediante un índice que no existe, en lugar de llamar al método, como Add, que existe para este propósito.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. El ejemplo siguiente se intenta agregar un elemento a una colección mediante un índice que no existe, en lugar de llamar a la List<T>.Add método.The following example attempts to add an element to a collection by using a non-existent index rather than calling the List<T>.Add method.

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main()
       {
          var numbers = new List<int>();
          numbers.AddRange( new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20 } );
          
          var squares = new List<int>();
          for (int ctr = 0; ctr < numbers.Count; ctr++)
             squares[ctr] = (int) Math.Pow(numbers[ctr], 2); 
       }
    }
    // 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()
    
    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()
    

    El fragmento de código siguiente corrige este error:The following code fragment corrects this error:

    var squares = new List<int>();
    for (int ctr = 0; ctr < numbers.Count; ctr++)
       squares.Add((int) Math.Pow(numbers[ctr], 2)); 
    
    Dim squares As New List(Of Integer)
    For ctr As Integer = 0 To numbers.Count - 1
       squares.Add(CInt(numbers(ctr) ^ 2)) 
    Next
    
  • Está intentando recuperar un elemento cuyo índice es negativo.You're attempting to retrieve an item whose index is negative. Esto suele ocurrir porque buscamos en una colección para el índice de un elemento concreto y erróneamente se supone que la búsqueda es correcta.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. En el ejemplo siguiente, la llamada a la List<T>.FindIndex(Predicate<T>) método no puede encontrar una cadena igual a "Z" y lo devuelve -1.In the following example, the call to the List<T>.FindIndex(Predicate<T>) method fails to find a string equal to "Z" and so returns -1. Sin embargo, este es un valor de índice no válido.However, this is an invalid index value.

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main()
       {
          var list = new List<String>(); 
          list.AddRange( new String[] { "A", "B", "C" } );
          // Get the index of the element whose value is "Z".
          int index = list.FindIndex((new StringSearcher("Z")).FindEquals);
          try {
             Console.WriteLine("Index {0} contains '{1}'", index, list[index]); 
          }
          catch (ArgumentOutOfRangeException e) {
             Console.WriteLine(e.Message);
          }
       }
    }
    
    internal class StringSearcher
    {
       String value;
       
       public StringSearcher(String value)
       {
          this.value = value;
       }
       
       public bool FindEquals(String s) 
       {
          return s.Equals(value, StringComparison.InvariantCulture); 
       }
    }
    // 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
    
    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
    

    Para evitar la excepción, compruebe que la búsqueda tiene éxito porque nos aseguramos de que el índice devuelto es mayor que o fragmento es igual a cero antes de intentar recuperar el elemento de la colección, como el siguiente código realiza.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".
    int index = list.FindIndex((new StringSearcher("Z")).FindEquals);
    if (index >= 0)
       Console.WriteLine("'Z' is found at index {0}", list[index]); 
    
    ' 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
    
  • Está intentando recuperar un elemento cuyo índice es igual al valor de la colección Count propiedad, como en el ejemplo siguiente se muestra.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.

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main()
       {
          var list = new List<String>(); 
          list.AddRange( new String[] { "A", "B", "C" } );
          try {
             // Display the elements in the list by index.
             for (int ctr = 0; ctr <= list.Count; ctr++) 
                Console.WriteLine("Index {0}: {1}", ctr, list[ctr]);
          } 
          catch (ArgumentOutOfRangeException e) {
             Console.WriteLine(e.Message);
          }
       }
    }
    // 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
    
    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
    

    Dado que las colecciones en .NET Framework usan indización de base cero, es el primer elemento de la colección en el índice 0 y el último elemento está en el índice Count - 1.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. Puede eliminar el error asegurándose de que tener acceso el último elemento en el índice Count - 1, como hace el código siguiente.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 (int ctr = 0; ctr < list.Count; ctr++) 
       Console.WriteLine("Index {0}: {1}", ctr, list[ctr]);
    
    ' 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   
    

Está intentando realizar una operación de cadena mediante una llamada a un método de manipulación de cadenas y el índice de inicio no existe en la cadena.You are attempting to perform a string operation by calling a string manipulation method, and the starting index does not exist in the string.
Las sobrecargas de métodos, como por ejemplo, String.Compare, String.CompareOrdinal, String.IndexOf, IndexOfAny, String.Insert, String.LastIndexOf, String.LastIndexOfAny, Remove, o String.Substring que le permiten especificar el índice inicial de la operación requieren que el índice sea una posición válida dentro de la cadena.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. Índices válidos van de 0 a String.Length - 1.Valid indexes range from 0 to String.Length - 1.

Hay cuatro causas comunes de este ArgumentOutOfRangeException excepción:There are four common causes of this ArgumentOutOfRangeException exception:

  • Está trabajando con una cadena vacía., o String.Empty.You are working with an empty string., or String.Empty. Dado que su String.Length propiedad devuelve 0, cualquier intento de manipular índice produce una ArgumentOutOfRangeException excepción.Because its String.Length property returns 0, any attempt to manipulate it by index throws an ArgumentOutOfRangeException exception. El ejemplo siguiente, se define un GetFirstCharacter método que devuelve el primer carácter de una cadena.The following example, defines a GetFirstCharacter method that returns the first character of a string. Si la cadena está vacía, que se pasa la cadena final para el método es, el método produce una ArgumentOutOfRangeException excepción.If the string is empty, as the final string passed to the method is, the method throws an ArgumentOutOfRangeException exception.

    using System;
    
    public class Example
    {
       public static void Main()
       {
           String[] words = { "the", "today", "tomorrow", " ", "" };
           foreach (var word in words)
              Console.WriteLine("First character of '{0}': '{1}'", 
                                word, GetFirstCharacter(word));
       }
       
       private static char GetFirstCharacter(String s)
       {
          return s[0];
       }
    }
    // 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()
    
    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()
    

    Puede eliminar la excepción mediante la comprobación de si la cadena String.Length es mayor que cero o mediante una llamada a la IsNullOrEmpty método para asegurarse de que la cadena no es null o está vacío.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. El siguiente fragmento de código realiza la segunda opción.The following code fragment does the latter. En este caso, si la cadena es null o está vacío, el GetFirstCharacter método devuelve u+0000.In this case, if the string is null or empty, the GetFirstCharacter method returns U+0000.

    static char GetFirstCharacter(String s)
    {
       if (String.IsNullOrEmpty(s)) 
          return '\u0000';
       else   
          return s[0];
    }
    
    Function GetFirstCharacter(s As String) As Char
       If String.IsNullOrEmpty(s) Then 
          Return ChrW(0)
       Else   
          Return s(0)
       End If   
    End Function
    
  • Manipular una cadena basándose en la posición de una subcadena dentro de esa cadena, y no se pudo determinar si realmente se ha encontrado la subcadena.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.

    El ejemplo siguiente extrae la segunda palabra de una frase de contraseña de dos palabras.The following example extracts the second word of a two-word phrase. Produce un ArgumentOutOfRangeException excepción si la frase consta de sólo una palabra y, por lo tanto, no contiene un carácter de espacio incrustado.It throws an ArgumentOutOfRangeException exception if the phrase consists of only one word, and therefore does not contain an embedded space character. Esto ocurre porque la llamada a la String.IndexOf(String) método devuelve -1 para indicar que la búsqueda y, a continuación, se pasa este valor no válido para el String.Substring(Int32) método.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.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          String[] phrases = { "ocean blue", "concerned citizen", 
                               "runOnPhrase" };
          foreach (var phrase in phrases)
             Console.WriteLine("Second word is {0}", GetSecondWord(phrase));
       }
      
       static String GetSecondWord(String s)
       {
          int pos = s.IndexOf(" ");
          return s.Substring(pos).Trim();
       }
    }
    // 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()
    
    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()
    

    Para eliminar la excepción, validar el valor devuelto por el método de búsqueda de cadenas antes de llamar al método de manipulación de cadenas.To eliminate the exception, validate the value returned by the string search method before calling the string manipulation method.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          String[] phrases = { "ocean blue", "concerned citizen", 
                               "runOnPhrase" };
          foreach (var phrase in phrases) {
             String word = GetSecondWord(phrase);
             if (! String.IsNullOrEmpty(word))
                Console.WriteLine("Second word is {0}", word);
          }   
       }
      
       static String GetSecondWord(String s)
       {
          int pos = s.IndexOf(" ");
          if (pos >= 0)
             return s.Substring(pos).Trim();
          else
             return String.Empty;   
       }
    }
    // The example displays the following output:
    //       Second word is blue
    //       Second word is citizen
    
    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
    

-

Ha intentado extraer una subcadena que está fuera del intervalo de la cadena actual.You've attempted to extract a substring that is outside the range of the current string.
Los métodos que extracción subcadenas que todas requieren que se especifique la posición inicial de la subcadena y, para las subcadenas que no continúan hasta el final de la cadena, el número de caracteres de la subcadena.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. Tenga en cuenta que esto no es el índice del último carácter de la subcadena.Note that this is not the index of the last character in the substring.

Un ArgumentOutOfRangeException excepción se produce normalmente en este caso porque incorrectamente ha calculado el número de caracteres de la subcadena.An ArgumentOutOfRangeException exception is typically thrown in this case because you've incorrectly calculated the number of characters in the substring. Si usa un método de búsqueda como String.IndexOf para identificar el inicio posiciones inicial y final de una subcadena:If you are using a search method like String.IndexOf to identify the starting and ending positions of a substring:

  • Si devuelve el carácter en la posición final String.IndexOf debe incluirse en la subcadena, la posición final de la subcadena se determina mediante la fórmulaIf 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  
    
  • Si el carácter en la posición final devuelto por String.IndexOf es que se excluirán de la subcadena, la posición final de la subcadena se determina mediante la fórmulaIf 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   
    

En el ejemplo siguiente se define un FindWords método que usa el String.IndexOfAny(Char[], Int32) método para identificar los caracteres de espacio y signos de puntuación marca en una cadena y devuelve una matriz que contiene las palabras que se encuentra en la cadena.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.

using System;
using System.Collections.Generic;

public class Example
{
   public static void Main()
   {
      String sentence = "This is a simple, short sentence.";
      Console.WriteLine("Words in '{0}':", sentence);
      foreach (var word in FindWords(sentence))
         Console.WriteLine("   '{0}'", word);
   }
   
   static String[] FindWords(String s)
   {
      int start = 0, end = 0;
      Char[] delimiters = { ' ', '.', ',', ';', ':', '(', ')' };
      var words = new List<String>();

      while (end >= 0) {
         end = s.IndexOfAny(delimiters, start);
         if (end >= 0) {
            if (end - start > 0)
               words.Add(s.Substring(start, end - start)); 

            start = end++;
         }
         else {
            if (start < s.Length - 1)
               words.Add(s.Substring(start));
         }
      }    
      return words.ToArray();                         
   }
}
// The example displays the following output:
//       Words in 'This is a simple, short sentence.':
//          'This'
//          'is'
//          'a'
//          'simple'
//          'short'
//          'sentence'
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'

Un número negativo ha pasado a un método con un argumento que requiera sólo números positivos y cero o ha pasado un número negativo o cero para un método con un argumento que requiera sólo números positivos.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.
Por ejemplo, el Array.CreateInstance(Type, Int32, Int32, Int32) método requiere que especifique el número de elementos de cada dimensión de una matriz bidimensional; los valores válidos para cada dimensión pueden oscilar entre 0 y Int32.MaxValue.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. Pero dado que el argumento de la dimensión en el ejemplo siguiente tiene un valor negativo, el método produce una ArgumentOutOfRangeException excepción.But because the dimension argument in the following example has a negative value, the method throws an ArgumentOutOfRangeException exception.

using System;

public class Example
{
   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
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

Para corregir el error, asegúrese de que el valor del argumento no válido es no negativo.To correct the error, ensure that the value of the invalid argument is non-negative. Puede hacer esto proporcionando un valor válido, como hace el siguiente fragmento de código.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);   
Dim dimension1 As Integer = 10
Dim dimension2 As Integer = 10
Dim arr As Array = Array.CreateInstance(GetType(String), 
                                        dimension1, dimension2)   

También puede validar la entrada y, si no es válido, realizar alguna acción.You can also validate the input and, if it is invalid, take some action. El fragmento de código siguiente muestra un mensaje de error en lugar de llamar al método.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 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

Existe una condición de carrera en una aplicación es multiproceso o tiene que ejecutar de forma asincrónica y que actualiza una matriz o colección de tareas.A race condition exists in an app that is multithreaded or has tasks that execute asynchronously and that updates an array or collection.
En el ejemplo siguiente se usa un List<T> objeto para rellenar una colección de Continent objetos.The following example uses a List<T> object to populate a collection of Continent objects. Produce un ArgumentOutOfRangeException excepción si el ejemplo se intenta mostrar los siete elementos de la colección antes de la colección esté completa.It throws an ArgumentOutOfRangeException exception if the example attempts to display the seven items in the collection before the collection is fully populated.

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 Example
{
   static List<Continent> continents = new List<Continent>();
   static String 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(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();
      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()
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()

En este caso, los dos recursos se obtiene acceso desde varios subprocesos:In this case, two resources are accessed from multiple threads:

  • Colección de continents.The continents collection. Su List<T>.Add se llama al método desde varios subprocesos.Its List<T>.Add method is called from multiple threads. Además, el subproceso principal o primario supone que la colección esté completa con siete elementos cuando recorre en iteración sus miembros.In addition, the main or primary thread assumes the collection is fully populated with seven elements when it iterates its members.

  • El msg cadena, que se concatena desde varios subprocesos.The msg string, which is concatenated from multiple threads.

Para corregir el error, asegúrese de que el estado compartido se tiene acceso de forma segura para subprocesos, como se indica a continuación.To correct the error, ensure that shared state is accessed in a thread-safe way, as follows.

  • Si su aplicación usa un objeto de matriz o colección, considere el uso de una clase de colección segura para subprocesos, como los tipos en el System.Collections.Concurrent espacio de nombres o el System.Collections.Immutable versión fuera de banda.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.

  • Asegúrese de que se accede al estado compartido (es decir, los recursos que pueden acceder varios subprocesos) de una manera segura para subprocesos, para que sólo un subproceso cada vez tenga acceso exclusivo a los recursos.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. Un gran número de clases, como CountdownEvent, Interlocked, Monitor, y Mutex, están disponibles para sincronizar el acceso a los recursos.A large number of classes, such as CountdownEvent, Interlocked, Monitor, and Mutex, are available to synchronize access to resources. Para obtener más información, consulte subprocesamiento.For more information, see Threading. Además, la compatibilidad de idioma está disponible a través del bloqueo instrucción en C# y el SyncLock construir en Visual Basic.In addition, language support is available through the lock statement in C# and the SyncLock construct in Visual Basic.

Las siguientes direcciones de ejemplo la ArgumentOutOfRangeException excepciones y otros problemas del ejemplo anterior.The following example addresses the ArgumentOutOfRangeException exception and the other issues from the previous example. Reemplaza el List<T> objeto con un ConcurrentBag<T> objeto para asegurarse de que el acceso a la colección es segura para subprocesos, usa un CountdownEvent objeto para asegurarse de que el subproceso de la aplicación continúa después de otros subprocesos se han ejecutado y usa un bloqueo para garantizar que sólo un subproceso puede tener acceso a la msg variable a la vez.It replaces the List<T> object with a ConcurrentBag<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.

using System;
using System.Collections.Concurrent;
using System.Threading;

public class Continent
{
   public String Name { get; set; }
   public int Population { get; set; }
   public Decimal Area { get; set; }   
}

public class Example
{
   static ConcurrentBag<Continent> continents = new ConcurrentBag<Continent>();
   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(PopulateContinents);
         th.Start(name);
      }              

      // Display the list.
      gate.Wait();
      Console.WriteLine(msg);
      Console.WriteLine();

      var arr = continents.ToArray();
      for (int ctr = 0; ctr < names.Length; ctr++) {
         var continent = arr[ctr];
         Console.WriteLine("{0}: Area: {1}, Population {2}", 
                           continent.Name, continent.Population,
                           continent.Area);
      }
   }
   
   private static void PopulateContinents(Object obj)
   {
      String name = obj.ToString();
      lock(msg) { 
         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(25);
      continents.Add(continent);
      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
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 utiliza HRESULT COR_E_ARGUMENTOUTOFRANGE, que tiene el valor 0 x 80131502.ArgumentOutOfRangeException uses the HRESULT COR_E_ARGUMENTOUTOFRANGE, which has the value 0x80131502.

Para obtener una lista de valores de propiedad iniciales de una instancia de ArgumentOutOfRangeException, consulte el ArgumentOutOfRangeException constructores.For a list of initial property values for an instance of ArgumentOutOfRangeException, see the ArgumentOutOfRangeException constructors.

Constructores

ArgumentOutOfRangeException()

Inicializa una nueva instancia de la clase ArgumentOutOfRangeException. Initializes a new instance of the ArgumentOutOfRangeException class.

ArgumentOutOfRangeException(SerializationInfo, StreamingContext)

Inicializa una nueva instancia de la clase ArgumentOutOfRangeException con datos serializados. Initializes a new instance of the ArgumentOutOfRangeException class with serialized data.

ArgumentOutOfRangeException(String)

Inicializa una nueva instancia de la clase ArgumentOutOfRangeException con el nombre del parámetro que causa esta excepción. Initializes a new instance of the ArgumentOutOfRangeException class with the name of the parameter that causes this exception.

ArgumentOutOfRangeException(String, Exception)

Inicializa una nueva instancia de la clase ArgumentOutOfRangeException con el mensaje de error especificado y la excepción que causó esta excepción. 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)

Inicializa una nueva instancia de la clase ArgumentOutOfRangeException con el nombre del parámetro, el valor del argumento y el mensaje de error especificados. 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)

Inicializa una nueva instancia de la clase ArgumentOutOfRangeException con el nombre del parámetro que provoca esta excepción y un mensaje de error especificados. Initializes a new instance of the ArgumentOutOfRangeException class with the name of the parameter that causes this exception and a specified error message.

Propiedades

ActualValue

Obtiene el valor del argumento que causa esta excepción. Gets the argument value that causes this exception.

Data

Obtiene una colección de pares clave-valor que proporcionan información adicional definida por el usuario acerca de la excepción. Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(Inherited from Exception)
HelpLink

Obtiene o establece un vínculo al archivo de ayuda asociado a esta excepción. Gets or sets a link to the help file associated with this exception.

(Inherited from Exception)
HResult

Obtiene o establece HRESULT, un valor numérico codificado que se asigna a una excepción específica. Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(Inherited from Exception)
InnerException

Obtiene la instancia Exception que produjo la excepción actual. Gets the Exception instance that caused the current exception.

(Inherited from Exception)
Message

Obtiene el mensaje de error y la representación de cadena del valor del argumento no válido. Si el valor del argumento es nulo, obtiene sólo el mensaje de error. 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

Obtiene el nombre del parámetro que causa esta excepción. Gets the name of the parameter that causes this exception.

(Inherited from ArgumentException)
Source

Devuelve o establece el nombre de la aplicación o del objeto que generó el error. Gets or sets the name of the application or the object that causes the error.

(Inherited from Exception)
StackTrace

Obtiene una representación de cadena de los marcos inmediatos en la pila de llamadas. Gets a string representation of the immediate frames on the call stack.

(Inherited from Exception)
TargetSite

Obtiene el método que produjo la excepción actual. Gets the method that throws the current exception.

(Inherited from Exception)

Métodos

Equals(Object)

Determina si el objeto especificado es igual al objeto actual. Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetBaseException()

Cuando se reemplaza en una clase derivada, devuelve la clase Exception que representa la causa principal de una o más excepciones posteriores. When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

(Inherited from Exception)
GetHashCode()

Sirve como la función hash predeterminada. Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext)

Establece el objeto SerializationInfo con el valor del argumento no válido e información adicional de la excepción. Sets the SerializationInfo object with the invalid argument value and additional exception information.

GetType()

Obtiene el tipo en tiempo de ejecución de la instancia actual. Gets the runtime type of the current instance.

(Inherited from Exception)
MemberwiseClone()

Crea una copia superficial del Object actual. Creates a shallow copy of the current Object.

(Inherited from Object)
ToString()

Crea y devuelve una representación de cadena de la excepción actual. Creates and returns a string representation of the current exception.

(Inherited from Exception)

Eventos

SerializeObjectState

Se produce cuando se serializa una excepción para crear un objeto de estados de excepción que contiene datos serializados sobre la excepción. Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(Inherited from Exception)

Se aplica a

Consultar también