IndexOutOfRangeException in C#


The IndexOutOfRangeException is an exception that will be thrown while accessing an element of a collection with an index that is outside of its range. It occurs when an invalid index is used to access a member of a collection.

The following example throws the IndexOutOfRange exception:

Example:

int[] arr = new int[5] { 10, 30, 25, 45, 65};
Console.WriteLine(arr[0]);
Console.WriteLine(arr[1]);
Console.WriteLine(arr[2]);
Console.WriteLine(arr[3]);
Console.WriteLine(arr[4]);
Console.WriteLine(arr[5]); // throws IndexOutOfRange exception

In the above example, an arr contains five elements. It will throw an IndexOutOfRange exception when trying to access value more than its total elements. Above, trying to access the 6th element using arr[5] will throw IndexOutOfRange exception.

Solutions to Prevent IndexOutOfRangeException

Solution 1: Get the total number of elements in a collection and then check the upper bound of a collection is one less than its number of elements.

The following example shows how to fix IndexOutOfRange exception:

Example:
int[] arr = new int[5] { 10, 30, 25, 45, 65};

Console.WriteLine(arr[0]);
Console.WriteLine(arr[1]);
Console.WriteLine(arr[2]);
Console.WriteLine(arr[3]);
Console.WriteLine(arr[4]);

if(arr.Length >= 6)
    Console.WriteLine(arr[5]);
}

Solution 2: Use the try catch blocks to catche the IndexOutOfRangeException.

Example:
static void Main()
{
    try
    {
        Console.WriteLine(arr[0]);
        Console.WriteLine(arr[1]);
        Console.WriteLine(arr[2]);
        Console.WriteLine(arr[3]);
        Console.WriteLine(arr[4]);
        Console.WriteLine(arr[5]); // throws IndexOutOfRange exception
    }
    catch(Exception ex)
    {
        Console.WriteLine("Error: {0}", ex.Message);
    }
}

In the above example, the entire code wrapped inside the try block may throw errors. The catch block has the Exception filter that can catch any exceptions. So, when the arr[5] statement inside the try block throws an exception, the catch block captures the IndexOutOfRange exception and displays an error message, and continues the execution.

Related Articles