019-001-009
Catching Multiple Exceptions
Medium
Problem Description
Catching Multiple Exceptions
In this problem, you will implement a processValue method that converts string array elements to integers, and verify that NumberFormatException and ArrayIndexOutOfBoundsException are thrown appropriately.
Learning Objective: Understand that multiple exception types can occur from a single method and learn how to handle each appropriately
Overview
The processValue() method retrieves an element from a static final string array within the class at the specified index and converts it to an integer. Appropriate exceptions are thrown for invalid indices or non-numeric strings.
Specifications
- Define a string array
{"10", "abc", "30"}as astatic finalfieldVALUESin the class processValue(int index)method (static):- Retrieves element with
VALUES[index]and converts to integer usingInteger.parseInt() - Out-of-bounds index →
ArrayIndexOutOfBoundsExceptionis thrown - Non-numeric string →
NumberFormatExceptionis thrown
- Retrieves element with
- Use try-catch in
main()to handle each case and output results or error messages
Test Method
Each test case calls Main.processValue(int) directly and verifies:
- Valid indices (e.g., 0, 2) return values without throwing exceptions
- Invalid indices (e.g., 1, 5) throw the appropriate exception
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