Question:
Java 1.5 introduced the Closeable
interface with one close()
method. In Java 1.7 the try-with-resources
was added and for this the AutoCloseable
interface was introduced, which was made the parent Closeable
interface.
As I understand it, this was done so that all classes that implement the Closeable
interface can be automatically used in a try-with-resources
. But then the meaning of entering this interface is not clear at all. Why not then make this operator work right away with the existing Closeable
interface rather than the new AutoCloseable
?
Or was it just so that the close()
method could throw any exceptions, not just inheritors from IOException
?
Answer:
There are two restrictions on the close
method of the Closeable
interface that we wanted to relax by introducing try-with-resources:
- Throwing only
IOException
, which is not suitable for everyone. For example for java.sql.Connection . - Idempotency requirement.
AutoCloseable
does not have it, although it is " highly recommended ".