Back to questions
JuniorTheoryCommon
What does the program print?
public class Main {
public static void main(String[] args) {
try (Door a = new Door("A"); Door b = new Door("B")) {
System.out.print(a.name() + b.name() + " ");
}
}
}
record Door(String name) implements AutoCloseable {
public void close() { System.out.print(name); }
}AB BA
- Expecting
AB AB: resources do not close in the order they were declared; try-with-resources closes them in reverse, the last one opened first. - Expecting a compile error over the missing
catch:AutoCloseable.close()declaresthrows Exception, butDoor.close()declares nothing, so there is nothing to catch.
- Why does try-with-resources close resources in reverse order?
- What happens when both the body and
close()throw an exception?