ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
try {
    try {
        throw new RuntimeException("inner");
    } finally {
        System.out.print("inner-finally ");
    }
} catch (RuntimeException e) {
    System.out.print("outer-catch:" + e.getMessage());
}
  1. A. outer-catch:inner inner-finally
  2. B. inner-finally outer-catch:inner
  3. C. inner-finally
  4. D. outer-catch:inner

Correct answer: B. inner-finally outer-catch:inner

The inner try's finally block always runs during unwinding, even though an exception is propagating out of the inner try; it runs BEFORE the exception reaches the outer catch. Output: inner-finally first, then outer-catch:inner.

More OOP with C++ and Java questions

Exams that ask this topic