Search code examples
javajava-7try-with-resourcesautocloseable

Does AutoCloseable.close() method break Backward compatibilty rule of Java


From Java 7 ,Closeable interface has been retrofitted to extend AutoCloseable interface so that all classes implementing Closeable interface can work with try-with-resources statement. Till now,Closeable interface was free to throw any exception including InterrruptedException. However,with Java 7 any instance of Closeable interface used in try-with-resources statement might throw InterruptedException when there is automatic invocation of close method after exiting the try block and its InterruptedException might get suppressed by implicit call to Throwable.addSuppressed(InterruptedException);

So does this break the backward compatibility rule of Java considering that somebody might have its exception unknowingly suppressed and program not behaving as it should


Solution

  • No, this doesn't break backwards compatibility. The "try-with-resources" feature was new in Java 7; old code couldn't call it. Any old code that relies on catching an exception thrown by close will still be using a normal "try-catch" block, and the exception won't be suppressed because it wouldn't be using "try-with-resources". Such a block wouldn't be able to be converted to "try-with-resources" because of the suppression, but it will still work as is.