ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
public class Main {
    static String f(int x) {
        try {
            if (x == 0) throw new ArithmeticException("div0");
            return "ok" + x;
        } catch (ArithmeticException e) {
            return "caught:" + e.getMessage();
        } finally {
            System.out.print("finally ");
        }
    }
    public static void main(String[] args) {
        System.out.println(f(0));
    }
}
  1. A. finally caught:div0
  2. B. caught:div0 finally
  3. C. finally \ncaught:div0 (on separate output then a newline)
  4. D. Compile-time error: cannot return from both try/catch and have a finally too

Correct answer: A. finally caught:div0

finally runs after the catch block has decided its return value (caught:div0) but before that value is actually handed back to the caller, so "finally " prints first (from inside f), and only then does println print the returned string, caught:div0.

More OOP with C++ and Java questions

Exams that ask this topic