Why introduce Autocloseable instead of expanding possible exceptions to Closeable
Why they added AutoCloseable
and changed Closeable
as follows:
public interface Closeable extends AutoCloseable {
public void close() throws IOException;
}
Instead of just changing Closeable
like this (no addition AutoCloseable
):
public interface Closeable {
public void close() throws Exception;
}
The advantages of the second solution would be: 1) Without the constraints of thrown exceptions (see IOException
) 2) Closeable
itself can be used in try-with-resources without extension AutoCloseable
3) This will not break existing code, because the implementation can only have exceptions that are more limited. than those defined in the interface 4) No retraining
Is there a reason why they chose to go with the first solution instead of the second instead?
source to share
You simply cannot change the checked exception list of already published methods. Otherwise, the old code may break. For example, a method like this might exist before Java 7:
public void closeAll(Collection<Closeable> collection) {
for(Closeable closeable : collection) {
try {
closeable.close();
}
catch(IOException ex) {
// ignore
}
}
}
After the change, you suggest this code not compile. Backward compatibility issues are taken very seriously by Java developers.
source to share
Good answer @ Tagir Valeev.
Closeable is in the system.io package and as Tagir said, Closeable.close throws an IOException - it is assumed to be related to I / O. AutoCloseable is in java.lang and AutoCloseable.close throws Exception.
With experience, a closer relationship has been found, not just for I / O.
source to share