Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 374
user1883212 Avatar asked Mar 15 '23 18:03

user1883212


2 Answers

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.

like image 178
Tagir Valeev Avatar answered Apr 07 '23 16:04

Tagir Valeev


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.

like image 24
Concrete Gannet Avatar answered Apr 07 '23 18:04

Concrete Gannet