Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Applicability section now notes that failing to use try-with-resources isn't a security vulnerability in and of itself, but that t-w-r makes it easy to get this issue right.

JDK 1.7 introduced the "try-with-resources" statement [JLS 2011] §14.20.3, "try-with-resources" that makes it much easier to deal with simplifies correct use of resources that implement the java.lang.AutoCloseable interface, including those that implement the java.io.Closeable interface.

Using the try-with-resources statement avoids problems that can arise when closing resources with an ordinary try-catch-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.

...

If only one exception is thrown, either during opening, processing, or closing of the files, the exception will be printed by the "thrown exception: " statement. If an exception is thrown during processing, and another one is thrown while trying to close either file, then the "thrown exception: " statement will print the exception encountered while closing the file, and the "suppressed exception: " statement will print the exception encountered during processing.

Applicability

Failing to use a try-with-resources statement when dealing correctly handle all failure cases when working with closeable resources may result in some resources not being closed, or important exceptions being masked, possibly resulting in a denial of service attack. 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 try-catch-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.

Bibliography