Is there AutoCloseable like class that doesn't throw Exception

119 Views Asked by At

Does any major Java library offer a AutoCloseable like interface for which close method doesn't throw exception? My close implementation is very simple and I'd like to avoid the boilerplate of catching the exception

1

There are 1 best solutions below

0
Slaw On

An object must be a java.lang.AutoCloseable in order to use it as a resource in a try-with-resources statement. But you can remove the throws clause from your implementation if it doesn't throw a checked exception.

For instance, if you have:

public class MyResource implements AutoCloseable {

    @Override
    public void close() {
        // perform cleanup
    }
}

Then the following will compile:

public void foo() {
    try (MyResource res = new MyResource()) {
        // use 'res'
    }
}

Without needing a catch block.

If you want, you can abstract this out into an interface.

public interface MyCloseable extends AutoCloseable {

    @Override
    void close();
}

Note you can instead make the exception more specific if needed. The java.io.Closeable interface inherits from AutoCloseable but changes the exception type to IOException.