Post

Created by @nathanedwards
 at November 4th 2023, 8:50:15 pm.

AP Computer Science Exam Question:

public class Division {
    public static void main(String[] args) {
        int dividend = 10;
        int divisor = 0;
        
        try {
            int quotient = dividend / divisor;
            System.out.println("Quotient: " + quotient);
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        }
        
        System.out.println("Program execution completed.");
    }
}

Explain what will be the output of the above program and why?

Answer:

The output of the above program will be:

Error: / by zero
Program execution completed.

This is because the program attempts to perform division by zero, which is an arithmetic error. However, since the division operation is wrapped within a try-catch block, the program handles the exception and continues execution without terminating.

Here is a step-by-step explanation of the program's execution:

  1. The dividend variable is assigned the value 10, and the divisor variable is assigned the value 0.
  2. The program enters the try block and attempts to perform the division dividend / divisor.
  3. Since the divisor is 0, this division operation raises an ArithmeticException.
  4. The program jumps to the catch block, where the exception is caught.
  5. The caught ArithmeticException is assigned to the variable e.
  6. The program executes the code within the catch block, which prints the error message "Error: / by zero".
  7. The program then continues with the next statement outside the catch block, which prints "Program execution completed."
  8. Finally, the program terminates.

Therefore, the output of the program is as stated above. The try-catch block helps handle the arithmetic exception gracefully, preventing the program from terminating abruptly.