Post

Created by @nathanedwards
 at November 3rd 2023, 4:13:42 pm.

AP Computer Science Exam Question

Question:

Consider the following Java code segment:

public class DivisionCalculator {

    public static int divideNumbers(int dividend, int divisor) {
        if (divisor == 0) {
            throw new ArithmeticException("Divisor cannot be zero");
        }
        return dividend / divisor;
    }

    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 0;
        
        try {
            int result = divideNumbers(num1, num2);
            System.out.println("Result of division: " + result);
        } catch (ArithmeticException e) {
            System.out.println("An exception occurred: " + e.getMessage());
        }
    }
}

Assuming the code segment is implemented correctly, what will be the output of running the program?

A. Result of division: 0
B. An exception occurred: Divisor cannot be zero
C. An exception occurred: / by zero
D. The program terminates abruptly

Explain your reasoning for selecting the correct option.

Answer:

The correct option is B. An exception occurred: Divisor cannot be zero.

The code segment begins by defining a class DivisionCalculator with a method divideNumbers which takes two integer arguments (dividend and divisor) and returns their division quotient. Inside the method, there is an if condition to check if the divisor is equal to zero. If it is, the method throws an ArithmeticException with the message "Divisor cannot be zero".

In the main method, two variables num1 and num2 are initialized with the values 10 and 0, respectively. Then, within a try block, the divideNumbers method is called with num1 and num2 as arguments and the result is stored in result variable. The statement System.out.println("Result of division: " + result); is executed if no exception occurs.

Considering that the divisor is indeed equal to zero in this case, the ArithmeticException will be thrown, and the program will proceed to the catch block. The catch block will print the message "An exception occurred: Divisor cannot be zero" using e.getMessage(), where e represents the caught ArithmeticException object.

Thus, the output of running the program will be B. An exception occurred: Divisor cannot be zero.