ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
public class Main {
    static void risky(int x) throws Exception {
        if (x < 0) throw new Exception("neg");
        System.out.print("ok");
    }
    public static void main(String[] args) {
        try {
            risky(-1);
        } catch (Exception e) {
            System.out.print("caught:" + e.getMessage());
        } finally {
            System.out.print(" done");
        }
    }
}
  1. A. ok done
  2. B. caught:neg done
  3. C. caught:neg
  4. D. ok caught:neg done

Correct answer: B. caught:neg done

risky(-1) throws before reaching the print("ok") line, so "ok" never prints. The catch block runs, printing caught:neg, and finally always runs afterward, printing " done". Result: caught:neg done.

More OOP with C++ and Java questions

Exams that ask this topic