ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
public class Main {
    public static void main(String[] args) {
        try {
            level1();
        } catch (RuntimeException e) {
            System.out.println("outer caught: " + e.getMessage());
        }
    }
    static void level1() {
        try {
            level2();
        } catch (NullPointerException e) {
            System.out.println("level1 caught NPE");
        }
    }
    static void level2() {
        throw new IllegalStateException("deep");
    }
}
  1. A. level1 caught NPE
  2. B. outer caught: deep
  3. C. Compilation error: level1 must declare throws
  4. D. The program crashes with no output

Correct answer: B. outer caught: deep

level1's catch only matches NullPointerException, so the actual IllegalStateException is not caught there and propagates up through level1's call stack to main, whose catch(RuntimeException e) does match it (IllegalStateException is a RuntimeException), printing "outer caught: deep".

More OOP with C++ and Java questions

Exams that ask this topic