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

  1. ArrayAccessor class:

    • static int getElement(int index) method:
      • Return the element at index in the internal array {10, 20, 30}
      • For an out-of-range index, ArrayIndexOutOfBoundsException is thrown naturally (do not use try-catch inside this method)
  2. Main class:

    • Call ArrayAccessor.getElement inside 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"

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