Introduction
ArrayIndexOutOfBoundsException
in Java is a runtime exception that occurs when an array is accessed with an invalid index. It helps identify errors related to array bounds in your code.
Table of Contents
- What is
ArrayIndexOutOfBoundsException
? - Common Causes
- Handling
ArrayIndexOutOfBoundsException
- Examples of
ArrayIndexOutOfBoundsException
- Conclusion
1. What is ArrayIndexOutOfBoundsException?
ArrayIndexOutOfBoundsException
is a subclass of IndexOutOfBoundsException
that indicates an illegal attempt to access an array element with an index outside the permissible range.
2. Common Causes
- Accessing an index less than zero.
- Accessing an index greater than or equal to the array length.
3. Handling ArrayIndexOutOfBoundsException
To handle ArrayIndexOutOfBoundsException
, use a try-catch block to catch the exception and take appropriate actions, such as logging the error or notifying the user.
4. Examples of ArrayIndexOutOfBoundsException
Example 1: Accessing an Invalid Index
This example demonstrates handling an ArrayIndexOutOfBoundsException
when accessing an index beyond the array length.
public class InvalidIndexExample { public static void main(String[] args) { int[] numbers = {1, 2, 3}; try { int value = numbers[3]; // Invalid index System.out.println("Value: " + value); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Error: Index out of bounds."); } } }
Output:
Error: Index out of bounds.
Example 2: Negative Index Access
This example shows how to catch an ArrayIndexOutOfBoundsException
when trying to access a negative index.
public class NegativeIndexExample { public static void main(String[] args) { int[] numbers = {1, 2, 3}; try { int value = numbers[-1]; // Negative index System.out.println("Value: " + value); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Error: Index cannot be negative."); } } }
Output:
Error: Index cannot be negative.
Conclusion
ArrayIndexOutOfBoundsException
is an important tool in Java for handling errors related to array bounds. By properly catching and managing this exception, you can ensure your application handles array access errors gracefully, leading to more robust and user-friendly code.