How to Handle ArrayIndexOutOfBounds Exception in Java?
Share
Condition for Handling ArrayIndexOutOfBounds Exception in Java
Description: To handle ArrayIndexOutOfBoundsException in Java, the try-catch block is used to manage cases where an attempt is made to access an array index beyond its valid range. The code that accesses the array is placed inside the try block, and if an invalid index is accessed, the catch block captures the exception, preventing the program from crashing. In the catch block, a suitable message can be logged or displayed to inform the user about the error. Additional logic, such as providing a default value or prompting for correct input, can also be implemented. Proper validation of array indices before accessing elements helps avoid this exception altogether, ensuring the index is within the valid range of 0 to array.length - 1.
Sample Source Code
# ArrayException.java
package JavaSamples2;
public class ArrayException {
public static void main(String args[]){
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // Accessing an invalid index
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Attempted to access an invalid array index.");
} finally {
System.out.println("Array processing complete.");
}
}
}
Screenshots
STEP 1: The ArrayIndexOutOfBoundsException will be displayed in the output window.