AP Computer Science Exam Question - Try-Catch Blocks
In a Java program, consider the following code segment:
public class TryCatchExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[4]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array Index Out Of Bounds!");
}
}
}
a) It handles a compile-time error.
b) It catches a runtime exception.
c) It checks if the array numbers
is empty.
d) It ensures that the element at index 4 of the array numbers
is accessed safely.
Answer:
Option b) It catches a runtime exception.
Explanation:
ArrayIndexOutOfBoundsException
.System.out.println(numbers[4]);
is executed, it tries to access an element at index 4 in the numbers
array. However, since arrays are zero-indexed in Java, and the numbers
array only has elements at indices 0, 1, and 2, accessing the element at index 4 will result in an ArrayIndexOutOfBoundsException
.try
block is intended for the potentially problematic code that might throw an exception. If an exception occurs within the try
block, the program flow is immediately transferred to the corresponding catch
block.catch
block with the appropriate ArrayIndexOutOfBoundsException
parameter is executed.catch
block then prints the error message "Error: Array Index Out Of Bounds!"
to the console.Thus, option b) accurately describes the purpose of the given try-catch block since it catches the specific runtime exception that might occur in the code segment.