VOOZH about

URL: https://www.geeksforgeeks.org/java/handle-a-java-lang-indexoutofboundsexception-in-java/

⇱ How to handle a java.lang.IndexOutOfBoundsException in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 20 Feb, 2024

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:


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.
Comment