简体   繁体   English

为什么要引入Autocloseable而不是在Closeable中扩展可能的异常

[英]Why introducing Autocloseable instead of extending the possible exceptions in Closeable

Why did they add the AutoCloseable and change the Closeable as follows: 为什么他们添加AutoCloseable并更改Closeable ,如下所示:

public interface Closeable extends AutoCloseable {
    public void close() throws IOException;
}

Instead of just changing Closeable as follows (without adding AutoCloseable ): 而不是仅仅更改Closeable如下(不添加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 第二种解决方案的优点是:1)没有生成异常的限制(参见IOException )2)可以在try-with-resources中使用Closeable本身而不必扩展AutoCloseable 3)这不会破坏现有代码,因为实现只能有比界面中定义的更有限的例外4)没有过度工程

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: 例如,在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. Java设计人员非常重视向后兼容性问题。

Nice answer @Tagir Valeev. 很好的答案@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. 可关闭在system.io包中,正如Tagir所说,Closeable.close抛出IOException - 它被认为与I / O相关。 AutoCloseable is in java.lang and AutoCloseable.close throws Exception. AutoCloseable在java.lang中,AutoCloseable.close抛出异常。

With experience, closeability was found to be a more general thing, not just specific to I/O. 根据经验,发现可靠性更为一般,而不仅仅是I / O特有的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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