11.12 try-with-Resources: Automatic Resource Deallocation

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 (introduced 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 could process a file with a try-with-resources statement to ensure that the file is closed properly when it’s no longer needed—we demonstrate this in Chapter 15. Each resource must be an object of a class that implements ...

Get Java™ How To Program (Early Objects), Tenth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.