A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/handle-a-java-lang-indexoutofboundsexception-in-java/ below:

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

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:

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:

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4