Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Typically resource-release code should be placed in a finally block to ensure that a resource is released, regardless of whether there were exceptions when the resource was used in the corresponding try block. An alternative notation—the try-with-resources statement (which is new in Java SE 7)—simplifies writing code in which you obtain one or more resources, use them in a try block and release them in a corresponding finally block. For example, a file-processing application (Chapter 17) could process a file with a try-with-resources statement to ensure that the file is closed properly when it’s no longer needed. Each resource must be an object of a class that implements the AutoCloseable interface—such a class has a close method. The general form of a try-with-resources statement is
try ( ClassName theObject = new ClassName() ) { // use theObject here } catch ( Exception e ) { // catch exceptions that occur while using the resource } |