Open In App

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

Last Updated : 20 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// 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:

  • The above Java program is the example of the handle a java.lang.IndexOutOfBoundException.
  • We already know this package handle the out of bound errors in the Java program.
  • In this, we can initialize the 3 elements that means it can save index 0 to 2 into the array but within try block we are accessing the element in index 3.
  • So, it’s out of bound then try block can handle this error during runtime then catch takes control print the error.

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads