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:
dividend
variable is assigned the value 10, and the divisor
variable is assigned the value 0.try
block and attempts to perform the division dividend / divisor
.divisor
is 0, this division operation raises an ArithmeticException
.catch
block, where the exception is caught.ArithmeticException
is assigned to the variable e
.catch
block, which prints the error message "Error: / by zero".catch
block, which prints "Program execution completed."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.