Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

IndexOutOfBoundsException — index outside the valid range

IndexOutOfBoundsException signals an index outside the permitted range. Learn its relationship to RuntimeException, its specialized subclasses, and how to validate an array index explicitly.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public IndexOutOfBoundsException()
public IndexOutOfBoundsException(String message)
public IndexOutOfBoundsException(int index)
public IndexOutOfBoundsException(long index)

java.lang.IndexOutOfBoundsException signals an index outside the range permitted by an operation. It extends RuntimeException, making it unchecked: the compiler does not require you to catch it or declare it with throws.

For array element access, a valid index satisfies 0 <= index && index < values.length. An index equal to the length is already invalid; an empty array has no valid indices. Direct array access with an invalid index throws ArrayIndexOutOfBoundsException. That class and StringIndexOutOfBoundsException extend IndexOutOfBoundsException, so a catch block for the base class also catches these exceptions.

Constructors accept no arguments or a String, int, or long argument. The numeric versions include the index in the message, but its exact format is unspecified. Do not make program logic depend on parsing those messages.

The example explicitly checks bounds and throws the exception with a custom message. Catching it serves demonstration purposes; in ordinary code, correct the index calculation or validate it at the API boundary rather than ignoring the exception and continuing with invalid assumptions.

Examples

public class Main {
    static int read(int[] values, int index) {
        if (index < 0 || index >= values.length) {
            throw new IndexOutOfBoundsException("Invalid index: " + index);
        }
        return values[index];
    }

    public static void main(String[] args) {
        int[] values = {10, 20};
        System.out.println(read(values, 1));
        try {
            System.out.println(read(values, 2));
        } catch (IndexOutOfBoundsException e) {
            System.out.println(e.getMessage());
        }
    }
}

Result

20
Invalid index: 2

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources