ProgrammingVery hardGATE CS · TCS NQT Prime · Product Company SDE

java class R implements AutoCloseable { public void close() { System.out.print("close"); } } try (R r = new R()) { System.out.print("body"); throw new…

class R implements AutoCloseable {
    public void close() { System.out.print("close"); }
}
try (R r = new R()) {
    System.out.print("body");
    throw new RuntimeException();
} catch (RuntimeException e) {
    System.out.print("catch");
}
What is printed?
  1. A. bodyclosecatch
  2. B. bodycatchclose
  3. C. bodyclose
  4. D. closebodycatch

Correct answer: A. bodyclosecatch

A try-with-resources block closes its resources as part of unwinding the try block, which happens before any catch clause runs; so body prints, then the thrown exception triggers close(), and only then is it caught.

More OOP with C++ and Java questions

Exams that ask this topic