Java ArrayIndexOutOfBoundsException
Example
Use an index that does not exist in an array, and catch the exception:
public class Main {
public static void main(String[] args) {
int[] myNumbers = {1, 2, 3};
try {
System.out.println(myNumbers[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("The index does not exist in the array.");
}
}
}
Definition and Usage
An ArrayIndexOutOfBoundsException happens when you use an index (a position) that does not exist in an array. Indexes start at 0, so in an array with 3 items, the last index is 2.
Check the index before you use it: it must be 0 or more, and less than myNumbers.length.
Related Pages
Java Exceptions (try...catch) Tutorial
❮ Errors & Exceptions