019-002-006
try-catch: Exception Handling
Hard
Problem Description
try-catch: Exception Handling
In this problem, you will implement the ArrayAccessor.getElement(int index) method. It accesses an internal array {10, 20, 30} and naturally throws ArrayIndexOutOfBoundsException for invalid indices. The Main class calls it safely using try-catch.
Learning Objective: Learn to properly catch and handle exceptions using try-catch statement
Overview
try-catch statement is a mechanism to catch exceptions that may occur at runtime, allowing programs to handle them appropriately without crashing.
Specifications
ArrayAccessorclass:static int getElement(int index)method:- Return the element at
indexin the internal array{10, 20, 30} - For an out-of-range index,
ArrayIndexOutOfBoundsExceptionis thrown naturally (do not use try-catch inside this method)
- Return the element at
Mainclass:- Call
ArrayAccessor.getElementinside try-catch blocks to handle exceptions - Access with index 1 (valid) → output "Value: 20"
- Access with index 5 (invalid) → output "Index out of bounds"
- Access with index 0 (valid) → output "Value: 10"
- Call
Output Format
Value: 20
Index out of bounds
Value: 10
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