I was reading this link for try-with-resources
and it says:
The close method of the
Closeable
interface throws exceptions of typeIOException
while the close method of theAutoCloseable
interface throws exceptions of typeException
.
But why? The close method of AutoCloseable
could have also thrown IOException
is there any example that support that close method of AutoCloseable
must throw exceptions of type Exception
Closeable extends IOException whereas AutoCloseable extends Exception. Closeable interface is idempotent (calling close() method more than once does not have any side effects) whereas AutoCloseable does not provide this feature. AutoCloseable was specially introduced to work with try-with-resources statements.
The AutoClosable interface is located in java. lang and is intended to be applied to any resource that needs to be closed 'automatically' (try-with-resources). The AutoClosable must not be an io releated resource. So the interface can not make any assumption of a concrete exception.
The try -with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java. lang. AutoCloseable , which includes all objects which implement java.
Interface Closeable A Closeable is a source or destination of data that can be closed. The close method is invoked to release resources that the object is holding (such as open files).
Closeable
extends AutoCloseable
, but there could be other particular interfaces that extend this interface. E.g.:
public interface MyCloseable extends AutoCloseable {
void close() throws RuntimeException;
}
They wanted to have an interface that can be used in many cases, and this is why they decided to use Exception
because it also works for other types of exceptions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With