简体   繁体   中英

Why introducing Autocloseable instead of extending the possible exceptions in Closeable

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM