Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why close method of java.lang.AutoCloseable throws Exception, but close method of java.io.Closeable throws IOException?

I was reading this link for try-with-resources and it says:

The close method of the Closeable interface throws exceptions of type IOException while the close method of the AutoCloseable interface throws exceptions of type Exception.

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

like image 477
Vishrant Avatar asked Sep 21 '14 13:09

Vishrant


People also ask

What is difference between closeable and AutoCloseable?

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.

What is the Java Lang AutoCloseable interface intended for?

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.

Which language feature ensures that object implementing the AutoCloseable interface are closed when it completes?

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.

What is the use of closeable interface in 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).


1 Answers

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.

like image 176
ROMANIA_engineer Avatar answered Sep 17 '22 15:09

ROMANIA_engineer