ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
class R implements AutoCloseable {
    public void close() {
        throw new IllegalStateException("close");
    }
}
// in main:
try (R r = new R()) {
    throw new RuntimeException("body");
} catch (Exception e) {
    System.out.print(e.getMessage() + " "
        + e.getSuppressed().length + " "
        + e.getSuppressed()[0].getMessage());
}
  1. A. An ArrayIndexOutOfBoundsException is thrown
  2. B. close 1 body
  3. C. close 0 body
  4. D. body 1 close

Correct answer: D. body 1 close

In try-with-resources, when the body throws and close() also throws, the body's exception is the one propagated and the exception from close() is attached to it as a suppressed exception. So the catch sees RuntimeException("body") with one suppressed IllegalStateException("close"). This is the opposite of a hand-written finally { r.close(); }, where the close exception would replace the body's.

More OOP with C++ and Java questions

Exams that ask this topic