CKTIS / C#
IndexOutOfRangeException — index outside bounds
System.IndexOutOfRangeException signals, among other cases, an attempt to read or write an array element using an invalid index. Usually, fix the index calculation or loop bounds rather than using the exception for normal control flow.
Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification
Syntax
array[index]
catch (System.IndexOutOfRangeException ex) { /* diagnostic handling */ }System.IndexOutOfRangeException is an exception thrown, among other cases, when reading or writing an array element outside its bounds. It usually indicates a coding error whose cause should be diagnosed and corrected rather than hidden by catching the exception.
For a one-dimensional int[] array, a valid index satisfies 0 <= index && index < values.Length. Length is the element count, not the last index. An empty array has no valid index. In a loop, use i < values.Length, not i <= values.Length; if you only need values, choose foreach.
Not every indexer throws the same exception. For an index below 0 or greater than or equal to Count, List<T> throws ArgumentOutOfRangeException, not IndexOutOfRangeException. The exception type depends on the API, despite the similar [] syntax.
The example deliberately reads values[values.Length] and catches the exception solely for demonstration. A correct loop then prints every element. In real code, correct the bounds or validate the index before access; do not treat catch as the normal condition for ending a loop.
Examples
using System;
internal static class Program
{
private static void Main()
{
int[] values = { 10, 20, 30 };
int index = values.Length;
try
{
Console.WriteLine(values[index]);
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine(ex.GetType().Name);
}
for (int i = 0; i < values.Length; i++)
{
Console.WriteLine(values[i]);
}
}
}Result
IndexOutOfRangeException 10 20 30
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.