Does close() method of the Closeable interface has exception in the signature

755 Views Asked by At

I was reading Closeable and AutoCloseable interface for the first time. As per my understanding we can't throw any exception apart from the IOException from close method of the Closeable interface and we can throw any possible exception like IllegalStateException only throw AutoCloseable Interface. But can we say that close() method of the Closeable method has exception in the signature.

2

There are 2 best solutions below

0
Shailesh Suryawanshi On BEST ANSWER

Are you trying to ask if Closable.close() has exception in the method signature?

Yes it does, you can check the documentation here: Closeable.close(). It throws IOException.

void close() throws Exception 

As per the documentation, Closeable extends AutoCloseable. We use it specifically dedicated to IO streams. Therefore it throws IOException instead of Exception.

From AutoCloseable.close():

While this interface method is declared to throw Exception, implementers are strongly encouraged to declare concrete implementations of the close method to throw more specific exceptions, or to throw no exception at all if the close operation cannot fail.

2
Gregor Zurowski On

The AutoCloseable interface defines the close method as follows:

void close() throws Exception

Whereas close in the Closeable interface, which extends AutoCloseable, is defined like this:

void close() throws IOException

Therefore you can only throw IOException or any exception extending from it in the latter case.

Please note that you can always throw any (unchecked) runtime exceptions like IllegalStateException independent of the exceptions defined on the method signature.