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

- 2,222
- 2
- 9
- 15
-
so that means that even void close() throws IOException this can throw IllegalStateException right? – Sia Saxena Jul 21 '21 at 07:42
-
1Yes, that is correct. If you look at the class hierarchy of `IllegalStateException` you will see that it extends from `RuntimeException`. As mentioned before, you can throw any runtime exception (also known as "unchecked exceptions") independent of the exceptions defined in the method signature. You might also want to review this post: https://stackoverflow.com/questions/2190161/difference-between-java-lang-runtimeexception-and-java-lang-exception – Gregor Zurowski Jul 21 '21 at 07:44
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.

- 6,399
- 1
- 30
- 52

- 1,190
- 7
- 12