Open In App

How to handle a java.lang.IndexOutOfBoundsException in Java?

In Java programming, IndexOutOfBoundsException is a runtime exception. It may occur when trying to access an index that is out of the bounds of an array. IndexOutOfBoundsException is defined as the RuntimeException. It can be used to find the out-of-bound run-time errors of an array. It is a part of the java.lang package.

In this article, we will learn how to handle a java.lang.IndexOutOfBoundsException in Java.



Syntax:

try {
   // write code
} 
catch (IndexOutOfBoundsException e) 
{
   // write code
}

Program to handle a java.lang.IndexOutOfBoundsException in Java

Below is the Program to handle a java.lang.IndexOutOfBoundsException:




// Java Program to handle a 
// java.lang.IndexOutOfBoundsException
import java.util.Arrays;
  
// Driver Class
public class GfGIndexOutOfBoundsException {
    // Main method
    public static void main(String args[]) 
    {
        // Array Intialization
        int[] array = {1, 2, 3};
        try 
        {
            // Attempt to access an element
            // outside the bounds of the array
            int value = array[3];  //  throw IndexOutOfBoundsException
              
              System.out.println("Value: " + value); 
        
        catch (IndexOutOfBoundsException e) 
        {
            // handle the exception and prints the message
            System.out.println("IndexOutOfBoundsException: " + e.getMessage());
        }
    }
}

Output

IndexOutOfBoundsException: Index 3 out of bounds for length 3


Explanation of the Program:

Article Tags :