Java ArrayIndexOutOfBoundsException Example

This Java example demonstrates the usage of java.lang.ArrayIndexOutOfBoundsException class with an example.
java.lang.ArrayIndexOutOfBoundsException has thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

ArrayIndexOutOfBoundsException Class Diagram


From the above class diagram, ArrayIndexOutOfBoundsException super classes are Exception, RuntimeException and IndexOutOfBoundsException.

Java ArrayIndexOutOfBoundsException Example

In this example, if an array is having only 3 elements and we are trying to display -1 or 4th element then it would throw this exception.
package com.javaguides.corejava;

public class ArrayIndexOutOfBounds {

    public static void main(String[] args) {

        int[] nums = new int[] {
            1,
            2,
            3
        };

        try {
            int numFromNegativeIndex = nums[-1]; // Trying to access at negative index
            int numFromGreaterIndex = nums[4]; // Trying to access at greater index
            int numFromLengthIndex = nums[3]; // Trying to access at index equal to size of the array
        } catch (ArrayIndexOutOfBoundsException e) {
            System.err.println("ArrayIndexOutOfBoundsException caught");
            e.printStackTrace();
        }
    }
}

Output

ArrayIndexOutOfBoundsException caught
java.lang.ArrayIndexOutOfBoundsException: -1
 at com.javaguides.corejava.ArrayIndexOutOfBounds.main(ArrayIndexOutOfBounds.java:10)
Fix Tip: We shouldn’t try to recover from this exception, we should try to mitigate it by checking if the index value passed is a valid value or not.

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course