Why did they add the AutoCloseable
and change the Closeable
as follows:
public interface Closeable extends AutoCloseable {
public void close() throws IOException;
}
Instead of just changing Closeable
as follows (without adding AutoCloseable
):
public interface Closeable {
public void close() throws Exception;
}
The advantages of the second solution would have been:
1) No limit of exceptions generated (see IOException
)
2) Closeable
itself could be used in try-with-resources without having to extend AutoCloseable
3) This wouldn't break existing code, because the implementation can only have exceptions that are more limited than the one defined in the interface
4) No overengineering
Is there any reason why instead they decided to go with the first solution and not the second one?
You simply cannot change the checked exception list of the already published methods. Otherwise the older code might become broken. For example such method might exist prior to Java 7:
public void closeAll(Collection<Closeable> collection) {
for(Closeable closeable : collection) {
try {
closeable.close();
}
catch(IOException ex) {
// ignore
}
}
}
After the change you propose this code would not compile. The backwards compatibility issues are taken very seriously by Java designers.
Nice answer @Tagir Valeev.
Closeable is in the system.io package and as Tagir said, Closeable.close throws IOException - it's assumed to be relevant to I/O. AutoCloseable is in java.lang and AutoCloseable.close throws Exception.
With experience, closeability was found to be a more general thing, not just specific to I/O.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With