Java program to handle ArrayIndexOutOfBoundsException

Java example to handle ArrayIndexOutOfBoundsException.
Submitted by Nidhi, on April 17, 2022

Problem Solution:

In this program, we will handle an Array Index Out of Bound Exception using try, catch block. The code that may generate an exception should be written in the try block, and the catch block is used to handle the exception and prevent program crashes.

Program/Source Code:

The source code to handle ArrayIndexOutOfBoundsException is given below. The given program is compiled and executed successfully.

// Java program to handle 
// ArrayIndexOutOfBoundsException

public class Main {
  public static void main(String[] args) {
    try {
      int arr[] = new int[10];

      arr[10] = 100;
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Exception: " + e);
    System.out.println("Program Finished");


Exception: java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10
Program Finished


In the above program, we created a class Main. The Main class contains a main() method. The main() method is the entry point for the program.

Here, we created "try" and "catch" blocks. In the "try" block, the Array Index out of bound exception gets generated because we created an array with size 10, which means the index will be from 0 to 9. But we tried to assign the value at index 10, which is out of the bound of the created array.

Here, we handled generated exceptions using the "catch" block and printed exception message.

Java Exception Handling Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.