ProgrammingVery hardAmazon/Microsoft SDE MCQ · Java placement

What is printed?

What is printed?
class R implements AutoCloseable {
    public void close() { throw new RuntimeException("C"); }
}
// in main:
try {
    try { throw new RuntimeException("A"); }
    finally { throw new RuntimeException("B"); }
} catch (RuntimeException e) { System.out.print(e.getMessage()); }
try (R r = new R()) {
    throw new RuntimeException("A");
} catch (RuntimeException e) {
    System.out.print(e.getMessage() + e.getSuppressed().length);
}
  1. A. AA1
  2. B. BC0
  3. C. BA1
  4. D. BA0

Correct answer: C. BA1

An exception thrown from finally replaces the pending one, and A is simply lost: B. In try-with-resources the body's exception A is primary and the exception from close() is attached to it as suppressed, so A1.

More OOP with C++ and Java questions

Exams that ask this topic