是否有类似 AutoCloseable 的类不会抛出异常

Han*_*lil 0 java autocloseable

是否有任何主要的 Java 库提供AutoCloseable类似的接口,其 close 方法不会抛出异常?我的关闭实现非常简单,我想避免捕获异常的样板

Sla*_*law 10

对象必须是 ajava.lang.AutoCloseable才能在try-with-resources语句中将其用作资源。throws但是,如果该子句不引发已检查的异常,则可以从实现中删除该子句。

例如,如果您有:

public class MyResource implements AutoCloseable {

    @Override
    public void close() {
        // perform cleanup
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将编译以下内容:

public void foo() {
    try (MyResource res = new MyResource()) {
        // use 'res'
    }
}
Run Code Online (Sandbox Code Playgroud)

无需catch块。

如果需要,您可以将其抽象为接口

public interface MyCloseable extends AutoCloseable {

    @Override
    void close();
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果需要,您可以使异常更加具体。该java.io.Closeable接口继承自AutoCloseable,但将异常类型更改为IOException.