ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
public class Main {
    static int risky() {
        try {
            return 1;
        } finally {
            return 2;
        }
    }
    public static void main(String[] args) {
        System.out.println(risky());
    }
}
  1. A. 1
  2. B. 2
  3. C. Compilation error: finally cannot contain return
  4. D. It throws an exception at run time

Correct answer: B. 2

A return inside finally discards any pending return (or exception) from the try block and becomes the method's actual result, so even though try computes 1 first, finally's return 2 overrides it and 2 is what's returned.

More OOP with C++ and Java questions

Exams that ask this topic