019-003-008
Using Multiple Catch Blocks
Easy
Problem Description
Using Multiple Catch Blocks
In this problem, you will implement a convertToInt method that converts a string to an integer, and a getElement method that retrieves an element from a string array. Each method throws NumberFormatException or ArrayIndexOutOfBoundsException depending on the arguments.
Learning Objective: Understand how to handle different exception types individually using multiple catch blocks
Overview
In a try-catch statement, multiple catch blocks can be placed sequentially to handle different exception types individually. More specific exception types must be written first.
Methods to Implement
convertToInt(String s) → int
- Convert string
sto an integer and return it - Throw
NumberFormatExceptionif conversion is not possible
getElement(String[] arr, int index) → String
- Return the element at
indexin arrayarr - Throw
ArrayIndexOutOfBoundsExceptionif the index is out of range
Examples
convertToInt("10") // → 10
convertToInt("abc") // → NumberFormatException
getElement(new String[]{"10","abc","20"}, 1) // → "abc"
getElement(new String[]{"10","abc","20"}, 5) // → ArrayIndexOutOfBoundsException
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