Auto close with try-with-resources in Java 7 and later
In Java SE 7 and later, for resource implements the interface java.lang.AutoCloseable, when the resource instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly.
Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. However, exception still can be throw from the finally block. The exception thrown from the try-with-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions.
In this case, it means you don't need to write something like
Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. However, exception still can be throw from the finally block. The exception thrown from the try-with-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions.
In this case, it means you don't need to write something like
myfile.close();inside the block anymore.
Comments
Post a Comment