019-001-007
Catching and Handling Exceptions
Easy
Problem Description
Array Access and Exceptions
In this problem, you will implement the getElement method that receives an integer array and an index, and returns the element at that index. If the index is out of bounds, an ArrayIndexOutOfBoundsException is thrown.
Learning Objective: Understand how ArrayIndexOutOfBoundsException occurs during array index access
Specifications
- Implement
public static int getElement(int[] arr, int index) - Return
arr[index]when the index is valid (0 or greater, less thanarr.length) - An
ArrayIndexOutOfBoundsExceptionis thrown for out-of-bounds indices (negative or ≥ array length)
Examples
getElement([10, 20, 30], 0) // => 10
getElement([10, 20, 30], 5) // => ArrayIndexOutOfBoundsException
getElement([10, 20, 30], -1) // => 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