Post

Created by @nathanedwards
 at November 4th 2023, 8:13:05 pm.

Exam Question

Consider the following code snippet:

public class Division {
    public static void main(String[] args) {
        int dividend = 10;
        int[] divisors = {2, 5, 0};

        for (int divisor : divisors) {
            try {
                int quotient = dividend / divisor;
                System.out.println("Quotient: " + quotient);
            } catch (ArithmeticException e) {
                System.out.println("Divisor cannot be zero.");
            }
        }
    }
}

Explain the use of try-catch blocks in the above code. Describe what happens when the code is executed, including the output it produces.

Answer

The try-catch blocks in the given code are used to handle the ArithmeticException that may occur when attempting to perform division.

When the code is executed, it initializes an int variable dividend with a value of 10 and an int array divisors with the values 2, 5, and 0.

The code then enters a for-each loop that iterates over each divisor in the divisors array. Inside the loop, the code attempts to perform the division dividend / divisor.

However, since dividing by zero is not allowed in mathematics, an ArithmeticException will be thrown when the divisor is zero. To handle this exception, a try-catch block is used.

When an ArithmeticException is thrown, the catch block is executed, and the message "Divisor cannot be zero." is printed to the console.

Therefore, when the code is executed, the following output is produced:

Quotient: 5
Divisor cannot be zero.

The first iteration of the loop successfully performs the division (10 / 2), resulting in a quotient of 5, which is then printed to the console.

In the second iteration, again the division (10 / 5) is successful, resulting in a quotient of 2, which is also printed to the console.

However, in the third iteration, the division (10 / 0) attempts to divide by zero, triggering the ArithmeticException. The catch block is executed, and the message "Divisor cannot be zero." is printed to the console.