import java.util.Objects;
public class CheckIndexExample {
public static void getElement(int[] arr, int index) {
// Ensure index is within array bounds
Objects.checkIndex(index, arr.length);
System.out.println("Element at index " + index + ": " + arr[index]);
}
public static void main(String[] args) {
int[] numbers = {5, 8, 9, 3, 0, 1};
try {
getElement(numbers, 1); // Valid index
getElement(numbers, 7); // Out of bounds, throws exception
} catch (IndexOutOfBoundsException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
/*
run:
Element at index 1: 8
ERROR!
Error: Index 7 out of bounds for length 6
*/