Exceptions · interview question
R prints "open X" in its constructor and "close X" in close(). Put the printed lines in order.
OrderingHard
R prints "open X" in its constructor and "close X" in close(). Put the printed lines in order.
try (R a = new R("A"); R b = new R("B")) {
System.out.println("body");
}Put the items in the correct order.
- open A
- close B
- close A
- body
- open B
Answer and explanation
Correct answer
1. open A
2. open B
3. body
4. close B
5. close A
Why
Resources are initialized in declaration order and closed in reverse order after the body, like nested try/finally blocks. That way a resource that depends on an earlier one is closed first.
References
Test yourself on Exceptions
A free test with instant, explained results. No account needed.
More Exceptions questions
- Explain checked vs unchecked exceptions in Java. When would you use each in your own API?
- Why does chaining exceptions in Java help in practice?
- Why can overusing exception wrapping become a problem in practice?
- Why wrap an exception with the original cause instead of replacing it completely?
- Which of the following is NOT a recommended practice for exception handling?
- Which method is used to retrieve the original cause of a chained exception?