Post

Created by @nathanedwards
 at November 4th 2023, 7:59:04 pm.

AP Computer Science Exam - Try-Catch Blocks

Question:

Consider the following code segment:

public class ExampleClass {
    public static void main(String[] args) {
        int[] numbers = {2, 4, 6, 8};
        
        try {
            for (int i = 0; i < 5; i++) {
                System.out.println(numbers[i]);
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index out of bounds.");
        }
        
        System.out.println("Program completed.");
    }
}

Assuming the code compiles correctly, what will be the output of running this program?

a) 2 4 6 8 Program completed. b) Array index out of bounds. Program completed. c) Compilation error due to an incorrect try-catch syntax. d) Array index out of bounds. Program will terminate without "Program completed." being printed.

Answer:

The correct answer is b) Array index out of bounds. Program completed.

Explanation:

In the given code segment, an array numbers is declared and initialized with elements {2, 4, 6, 8}.

The try block contains a for loop that iterates from 0 to 5. Inside the loop, the elements of the numbers array are printed using the index i as the array subscript.

However, the loop exceeds the size of the numbers array (which has only 4 elements) when i reaches 4. This results in an ArrayIndexOutOfBoundsException being thrown.

Since this exception is caught by the catch block with the parameter ArrayIndexOutOfBoundsException e, the message "Array index out of bounds." is printed to the console.

After executing the try-catch block, the statement System.out.println("Program completed."); is executed, which always prints "Program completed." regardless of the exception being caught.

Therefore, the output of running this program will be "Array index out of bounds. Program completed.", option b.