ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
public class Main {
    public static void main(String[] args) throws Exception {
        try {
            method1();
        } catch (RuntimeException e) {
            System.out.print("outer caught: " + e.getMessage());
        }
    }
    static void method1() {
        try {
            throw new IllegalStateException("bad state");
        } catch (NullPointerException e) {
            System.out.print("npe");
        }
    }
}
  1. A. npe
  2. B. outer caught: bad state
  3. C. Compile-time error: method1 must declare throws IllegalStateException
  4. D. Nothing: the exception is silently swallowed

Correct answer: B. outer caught: bad state

IllegalStateException does not match the catch (NullPointerException e) in method1, so it is not caught there and propagates up (unchecked exceptions need no throws declaration). main's catch (RuntimeException e) matches it (IllegalStateException is a RuntimeException), printing "outer caught: bad state".

More OOP with C++ and Java questions

Exams that ask this topic