Skip to main content Skip to docs navigation
TechSpiderTutorials

ArrayIndexOutOfBoundsException in Java

On this page

Java.lang.Long Class

Creating Objects

Default Constructor: This creates an instance without a message.

ArrayIndexOutOfBoundsException ex1 = new ArrayIndexOutOfBoundsException();
					

Constructor with Index:This constructor accepts an integer index, which can be useful to indicate which index was out of bounds.

ArrayIndexOutOfBoundsException ex2 = new ArrayIndexOutOfBoundsException(5); // Example index
					

Constructor with Message:You can also pass a custom error message.

ArrayIndexOutOfBoundsException ex3 = new ArrayIndexOutOfBoundsException("Index out of bounds: 5");
					

ArrayIndexOutOfBoundsException Class Example

public class ArrayIndexOutOfBoundsExceptionExample {
    public static void main(String[] args) {
        // Create an array of integers with 5 elements
        int[] numbers = {10, 20, 30, 40, 50};

        try {
            // Attempt to access an index that is out of bounds
            int index = 5; // Valid indices are 0 to 4
            System.out.println("Accessing index " + index + ": " + numbers[index]);
        } catch (ArrayIndexOutOfBoundsException e) {
            // Handle the exception
            System.out.println("Error: Index " + e.getMessage() + " is out of bounds!");
        } finally {
            System.out.println("Execution completed.");
        }
    }
}

Output:

Error: Index Index 5 out of bounds for length 5 is out of bounds!
                    Execution completed.