Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

IndexOutOfBoundsException

Thrown when a list or a string is accessed at an index outside the valid range.

Available since: Java 1.0

Syntax

public class IndexOutOfBoundsException extends RuntimeException

Examples

A list and a string:

void main() {
    List<String> list = List.of("a", "b");
    try {
        list.get(5);
    } catch (IndexOutOfBoundsException e) {
        IO.println(e.getMessage());
    }
    try {
        "abc".charAt(10);
    } catch (IndexOutOfBoundsException e) {
        IO.println(e.getClass().getSimpleName() + ": " + e.getMessage());
    }
}

Output:

Index: 5 Size: 2
StringIndexOutOfBoundsException: Index 10 out of bounds for length 3

Notes

It has subclasses: ArrayIndexOutOfBoundsException for arrays and StringIndexOutOfBoundsException for strings. Catching IndexOutOfBoundsException catches them all. To validate an index use Objects.checkIndex(index, length).

See also

Related recipes

In the tutorial

  • What exceptions are — Exceptions in Java — how a program reports an error, how to read a stack trace, common exceptions and the Throwable hierarchy.

Thanks for reading!

Donate to the site — we work hard for you.