ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
public class Main {
    static int divide(int a, int b) {
        try {
            return a / b;
        } catch (ArithmeticException e) {
            return -1;
        } finally {
            System.out.print("cleanup ");
        }
    }
    public static void main(String[] args) {
        System.out.println(divide(10, 0));
    }
}
  1. A. cleanup -1
  2. B. Exception in thread "main": ArithmeticException
  3. C. cleanup then the program crashes
  4. D. -1 cleanup

Correct answer: A. cleanup -1

10 / 0 throws ArithmeticException, caught by the catch block which decides to return -1; finally still runs before that value is actually handed back, printing "cleanup " first, and only then does println print the returned value, -1.

More OOP with C++ and Java questions

Exams that ask this topic