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 RuntimeExceptionExamples
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 3Notes
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
- ArrayIndexOutOfBoundsException — Thrown when an array is accessed at an index that does not exist.
- List.get() — Returns the list element at an index.
- List.subList() — Returns the part of a list between two indexes.
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.