Compartilhar via


Solucionando problemas de exceções: System.IndexOutOfRangeException

Um IndexOutOfRangeException exceção é lançada quando é feita uma tentativa de acessar um elemento de uma matriz ou coleção com um índice que está fora dos limites da matriz ou menor que zero.

Associated Tips

  • Certifique-se de que o índice máximo em uma lista é menor que o tamanho da lista
    The maximum index on a list must be less than the list size.

  • Certificar-se de que o índice não é um número negativo.
    This exception will be thrown if the index is less than zero.

  • Verifique se os nomes de coluna de dados estão corretos.
    Essa exceção pode ser lançada se o nome da coluna de dados sendo fornecido para o DataView.Sort a propriedade não é válida. For more information, see the DataView class.

Example

Description

O exemplo a seguir utiliza um Try…Catch bloco para interceptar a IndexOutOfRangeException índice quando i está fora dos limites da matriz, 0 a 3. O exemplo exibe o seguinte:

Element at index 0: 3

Element at index 2: 5

Element at index -1: IndexOutOfRangeException caught

Element at index 4: IndexOutOfRangeException caught

Code

Module Module1

    Sub Main()
        ' The first two tests will display the value of the array element.
        IndexTest(0)
        IndexTest(2)
        ' The following two calls will display the information that
        ' an IndexOutOfRangeException was caught.
        IndexTest(-1)
        IndexTest(4)
    End Sub

    Sub IndexTest(ByVal i As Integer)
        Dim testArray() As Integer = {3, 4, 5, 6}
        Console.Write("Element at index {0}: ", i)
        Try
            Console.WriteLine(testArray(i))
        Catch ex As IndexOutOfRangeException
            Console.WriteLine("IndexOutOfRangeException caught")
        End Try
    End Sub

End Module

Consulte também

Tarefas

Como: Use o Assistente de exceção

Referência

IndexOutOfRangeException

Conceitos

Matrizes no Visual Basic