ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
public class Main {
    static class Resource implements AutoCloseable {
        public void close() { System.out.print("closed "); }
    }
    public static void main(String[] args) {
        try (Resource r = new Resource()) {
            System.out.print("using ");
            throw new RuntimeException("oops");
        } catch (RuntimeException e) {
            System.out.print("caught:" + e.getMessage() + " ");
        }
    }
}
  1. A. using closed caught:oops
  2. B. using caught:oops closed
  3. C. closed using caught:oops
  4. D. using caught:oops

Correct answer: A. using closed caught:oops

The body prints "using ", then throws. Before that exception can be caught by the surrounding catch clause, the try-with-resources machinery closes every declared resource first, so "closed " prints next; only then does control reach the catch block, printing "caught:oops ".

More OOP with C++ and Java questions

Exams that ask this topic