Search code examples
javatry-catchtry-with-resources

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


Solution

  • 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.

    On the other hand Closable is located in java.io and extends AutoClosable, because a Closable is an AutoClosable for io resources. Therefore it declares that IOExceptions can be thrown on close.

    For example... a java.sql.Connection is an AutoClosable because it's close method throws SQLException and a SQLException is not an IOException. Think about in memory DBs and it makes sense that closing an sql connection must not throw an IOException.

    EDIT

    answered one more doubt i.e. why AutoClosable is kept under java.lang package. Thanks.

    I think it is located in java.lang because try-with-resources was introduced as a language feature in Java 1.7. Thus java.lang