Senior
What is the difference between AutoCloseable and Closeable?
sobes.tech AI
Answer from AI
The Closeable and AutoCloseable interfaces in Java are used for automatic resource management but have some differences:
Closeableis in thejava.iopackage and is intended for input/output streams. Theclose()method in this interface is declared to throwIOException.AutoCloseablewas introduced in Java 7 in thejava.langpackage and is more general. Theclose()method can throw any exception (Exception).
Closeable extends AutoCloseable, meaning all Closeable are AutoCloseable, but not vice versa.
This is important when using try-with-resources: if the resource implements Closeable, then the close exceptions are limited to IOException, but if only AutoCloseable, any exception can be thrown.
Example:
class MyResource implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("Closing resource");
}
}
try (MyResource r = new MyResource()) {
// work with the resource
}