The Java Development Kit 1.7 (JDK 1.7) introduced the try-with-resources statement (see the JLS, §14.20.3, "
try-with-resources" [JLS 2013]), which simplifies correct use of resources that implement the
java.lang.AutoCloseable interface, including those that implement the
Using the try-with-resources statement avoids problems that can arise when closing resources with an ordinary
finally block, such as failing to close a resource because an exception is thrown as a result of closing another resource, or masking an important exception when a resource is closed.
Use of the try-with-resources statement is also illustrated in ERR05-J. Do not let checked exceptions escape from a finally block, FIO03-J. Remove temporary files before termination, and FIO04-J. Release resources when they are no longer needed.
Noncompliant Code Example
This noncompliant code example uses an ordinary
finally block in an attempt to close two resources.
However, if an exception is thrown when the
br is closed, then the
bw will not be closed.
Compliant Solution (finally block)
This compliant solution uses a second
finally block to guarantee that
bw is properly closed even when an exception is thrown while closing
Compliant Solution (
This compliant solution uses a try-with-resources statement to manage both
This solution preserves any exceptions thrown during the processing of the input while still guaranteeing that both
bw are properly closed, regardless of what exceptions occur. Finally, this code demonstrates how to access every exception that may be produced from the try-with-resources block.
If only one exception is thrown, either during opening, processing, or closing of the files, the exception will be printed after
"thrown exception:". If an exception is thrown during processing, and a second exception is thrown while trying to close either file, the first exception will be printed after
"thrown exception:", and the second exception will be printed after
Failing to correctly handle all failure cases when working with closeable resources may result in some resources not being closed or in important exceptions being masked, possibly resulting in a denial of service. Note that failure to use a try-with-resources statement cannot be considered a security vulnerability in and of itself because it is possible to write a correctly structured group of nested
finally blocks guarding the resources that are in use (see ERR05-J. Do not let checked exceptions escape from a finally block). That said, failure to correctly handle such error cases is a common source of vulnerabilities. Use of a try-with-resources statement mitigates this issue by guaranteeing that the resources are managed correctly and that exceptions are never masked.