ArrayIndexOutOfBoundsException in Java
beginner· Exceptions · Error Handling
Problem
An ArrayIndexOutOfBoundsException is thrown when code tries to read or write an array position outside its valid range of 0 through length minus 1.
Access an array index beyond its valid range, and handle the resulting exception.
Input
int[] arr = {10, 20, 30, 40, 50}; arr[5]
Output
Error: Index 5 is out of bounds for this array
Java Program
Java
public class ArrayIndexOutOfBoundsExceptionDemo {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
try {
int value = arr[5]; // valid indices are 0 through 4
System.out.println("Value: " + value);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Index 5 is out of bounds for this array");
}
}
}Output
Error: Index 5 is out of bounds for this array
Core Logic
Wrapping the risky array access in try-catch lets an out-of-range index be caught and reported instead of crashing the program.
How It Works
- 1
int[] arr = {10, 20, 30, 40, 50};creates a 5-element array with valid indices 0 through 4. - 2
arr[5]requests a sixth element that doesn't exist — the array's last valid index is 4, not 5. - 3This throws an
ArrayIndexOutOfBoundsExceptionat the moment of access. - 4The
catch (ArrayIndexOutOfBoundsException e)block catches it and prints a message instead of letting the program crash.
Accessing
arr[5] on a 5-element array throws immediately, caught and printed as "Error: Index 5 is out of bounds for this array".💡
Key Point: Array indices are always zero-based, so a 5-element array's valid range is 0 through 4 — index 5 looks like it should be the 'fifth' element but is actually one past the end.
Key Concepts
try / catcharray boundsArrayIndexOutOfBoundsException