java – Closeable and AutoCloseable Interface Compatibility


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 ?


There are two restrictions on the close method of the Closeable interface that we wanted to relax by introducing try-with-resources:

  1. Throwing only IOException , which is not suitable for everyone. For example for java.sql.Connection .
  2. Idempotency requirement. AutoCloseable does not have it, although it is " highly recommended ".
Scroll to Top