ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Resource {
    Resource() {
        System.out.print("open ");
        throw new RuntimeException("ctor failed");
    }
    void close() { System.out.print("close "); }
}
public class Main {
    public static void main(String[] args) {
        try {
            Resource r = new Resource();
            r.close();
        } catch (RuntimeException e) {
            System.out.print("caught:" + e.getMessage());
        }
    }
}
  1. A. open close caught:ctor failed
  2. B. open caught:ctor failed
  3. C. Compile-time error: r is used before being fully assigned
  4. D. close caught:ctor failed

Correct answer: B. open caught:ctor failed

If a constructor throws, the object reference is never produced: r is never assigned, so r.close() never executes. Only "open " prints before the exception is thrown, then it propagates out of the new expression and is caught, printing caught:ctor failed.

More OOP with C++ and Java questions

Exams that ask this topic