.NET API Documentation

IndexOutOfRangeException Class

System

The exception that is thrown when the index of one of the arguments is outside the set of valid indices for the associated array or collection.

Inheritance

ObjectExceptionSystemExceptionIndexOutOfRangeException

Remarks

An IndexOutOfRangeException is thrown when the value of an array index or a collection index is outside the range of valid indices. For an array, valid indices range from zero to Length - 1. For a collection, the valid index range is determined by the collection's implementation.

This exception is a subclass of SystemException, which is the base class for all exceptions that are not error codes returned by the operating system.

The IndexOutOfRangeException exception occurs when you try to access an element in an array or collection using an index that is less than zero or greater than or equal to the number of elements in the collection.

Constructors

Name Description
IndexOutOfRangeException() Initializes a new instance of the IndexOutOfRangeException class.
IndexOutOfRangeException(String message) Initializes a new instance of the IndexOutOfRangeException class with a specified error message.
IndexOutOfRangeException(String message, Exception innerException) Initializes a new instance of the IndexOutOfRangeException class with a specified error message and a reference to the inner exception that is the cause of this exception.

Properties

Name Description
Message Gets the error message that explains the reason for the exception.
InnerException Gets a reference to the inner exception that is the cause of the current exception, if one is set.
StackTrace Gets a string representation of the immediate frame in the call stack.

Example Usage

The following code example demonstrates how to handle an IndexOutOfRangeException.


using System;

public class Example
{
    public static void Main(string[] args)
    {
        int[] numbers = { 1, 2, 3, 4, 5 };
        int index = 10;

        try
        {
            Console.WriteLine(numbers[index]);
        }
        catch (IndexOutOfRangeException ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
            Console.WriteLine($"Attempted to access index: {index}");
        }
    }
}
            

Output of the Example


Error: Index was outside the bounds of the array.
Attempted to access index: 10