Sub topic 3
AutoCloseable and Closeable
A resource is something your program borrows and must give back, like a file or a network connection. Java can return it for you automatically. To make that work, the resource must say how to close itself.
AutoCloseable and Closeable
An interface is a promise that a class has certain methods. AutoCloseable is an interface with one method, close(). Closeable is an older interface for input and output classes. It extends AutoCloseable, and its close() can throw IOException. Any class that implements either one can be used in try-with-resources.
Automatic Cleanup with try-with-resources
Try-with-resources is a try statement with the resource declared in parentheses. Java calls close() when the block ends. It does this whether the block finishes normally or throws an exception. You don't need a finally block.
Managing Multiple Resources
If you need more than one resource, separate them with semicolons. They close in reverse order, so the last one opened is the first one closed.
public class Door implements AutoCloseable {
private final String name;
Door(String name) {
this.name = name;
System.out.println("open " + name);
}
@Override
public void close() {
System.out.println("close " + name);
}
public static void main(String[] args) {
try (Door a = new Door("a"); Door b = new Door("b")) {
System.out.println("using doors");
}
}
}This prints open a, open b, using doors, close b, close a.
When close() Fails Too: Suppressed Exceptions
Sometimes the body throws an exception and then close() throws one too. Java keeps the first exception, the one from the body. The exception from close() is attached to it as a suppressed exception, so it isn't lost. You can read the suppressed exceptions with e.getSuppressed(), which returns an array.
catch (RuntimeException e) {
for (Throwable s : e.getSuppressed()) {
System.out.println("suppressed: " + s.getMessage());
}
}Reusing Existing Variables as Resources
Since Java 9, you can put an existing variable in the parentheses, like try (reader) { ... }. The variable must be effectively final, which means it is never assigned a new value after it is created.
Exception Handling Best Practices
- Catch specific types, like
IOException, and avoid catching plainException. - Never leave a catch block empty. At least log the error.
- When you wrap an exception in a new one, pass the original along as the cause.
- Use try-with-resources for anything that implements
AutoCloseable.
Exercise
In try (Door x = new Door("x"); Door y = new Door("y")) { }, which door closes first?
Show answer
Door y closes first, because resources close in the reverse of the order they were opened.
Exercise
The body of a try-with-resources block throws an exception, and then close() also throws. Which exception does your catch block receive?
Show answer
It receives the exception from the body. The exception from close() is attached to it and can be read with getSuppressed().