Exception Handling: try-catch Basics
Problem Description
Exception Handling: ArrayIndexOutOfBoundsException
In this problem, you will implement a static method accessArray(int index) that accesses elements in the array {10, 20, 30} by index. For valid indices, it returns the element value. For invalid indices, ArrayIndexOutOfBoundsException is thrown naturally.
Learning Objective: Understand how exceptions occur during array index access and learn to catch them using try-catch statements
Overview
In Java, accessing an array index outside the valid range (0 to length-1) automatically throws an ArrayIndexOutOfBoundsException. By implementing this method, you will understand when exceptions occur and learn how callers can handle them using try-catch.
Specifications
Implement the following static field and method:
static int[] array = {10, 20, 30};
static int accessArray(int index) {
// Return the array element at the given index
// Throws ArrayIndexOutOfBoundsException for invalid indices
}
Test Cases
| Call | Result |
|---|---|
accessArray(0) |
Returns 10 |
accessArray(2) |
Returns 30 |
accessArray(5) |
ArrayIndexOutOfBoundsException |
accessArray(-1) |
ArrayIndexOutOfBoundsException |
Hint
- Valid array indices are from
0toarray.length - 1 - For invalid indices, the Java runtime automatically throws an exception
- Try using try-catch in the main method to observe the behavior
Ready to Try Running Code?
Log in to access the code editor and execute your solutions for this problem.
Don't have an account?
Sign Up