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());
}- A. An ArrayIndexOutOfBoundsException is thrown
- B. close 1 body
- C. close 0 body
- 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
- What is printed? java class T { static int a = T.b + 1; static int b = 5; static int c = b + 1; } // in main: System.out.print(T.a + " " +…
- What is printed? java class K { static final int C = 10; static final Integer D = 20; static { System.out.print("K "); } } // in main…
- Which lines fail to compile? java interface I { static String id() { return "I"; } default String name() { return "N"; } } class C…
- What is printed? cpp struct B { virtual string who() const { return "B"; } }; struct D : B { string who() const override { return "D"; }…
- What is printed? cpp struct M { M() { cout << "m"; } ~M() { cout << "~m"; } }; struct B { B() { cout << "b"; f(); } virtual ~B() { cout <<…
- What is printed? cpp struct P { P(const char s) { cout << s; } }; struct B1 { B1() { cout << "1"; } }; struct B2 { B2() { cout << "2"; }…