ArrayIndexOutOfBoundsException
Thrown when an array is accessed at an index that does not exist.
Available since: Java 1.0
Syntax
public class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsExceptionExamples
The classic <= mistake in a loop:
void main() {
int[] nums = {1, 2, 3};
try {
for (int i = 0; i <= nums.length; i++) {
IO.println(nums[i]);
}
} catch (ArrayIndexOutOfBoundsException e) {
IO.println(e.getMessage());
}
}Output:
1
2
3
Index 3 out of bounds for length 3Notes
Array indexes go from 0 to length - 1. Most often the error comes from the condition i <= length instead of i < length, or from a negative index. A for-each loop over the array avoids it. For lists the parent class IndexOutOfBoundsException is thrown.
See also
- IndexOutOfBoundsException — Thrown when a list or a string is accessed at an index outside the valid range.
- RuntimeException — The base class of unchecked exceptions — bugs in program logic.
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.