Java Reference
In-Depth Information
occur.Finally,thiscodedemonstrateshowtoaccesseveryexceptionthatmaybeproduced
from the
try
-with-resources block.
If only one exception is thrown, 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 second
exception will be printed after
"thrown exception:"
, and the first exception will be
printed after
"suppressed exception:"
.
Applicability
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, pos-
sibly resulting in a denial of service. Note that failure to use a
try
-with-resources state-
ment 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
fi-
commonsourceofvulnerabilities.Useofa
try
-with-resourcesstatementmitigatesthisis-
suebyguaranteeingthattheresourcesaremanagedcorrectlyandthatexceptionsarenever
masked.
Bibliography
[JLS 2013]
§14.20.3, “
try
-with-resources”
[Long 2012]
ERR05-J. Do not let checked exceptions escape from a
finally
block
FIO03-J. Remove temporary files before termination
FIO04-J. Close resources when they are no longer needed
[Tutorials 2013]
The
try
-with-resources Statement