Java Reference
In-Depth Information
This code need not catch
ArrayIndexOutOfBoundsException
because it is a runtime
exception, and such exceptions indicate programmer errors, which are best resolved by
fixing the defect.
Applicability
Use of exceptions for any purpose other than detecting and handling exceptional condi-
tions complicates program analysis and debugging, degrades performance, and can in-
crease maintenance costs.
Bibliography
[Bloch 2001]
Item 39, “Use Exceptions Only for Exceptional Conditions”
[JLS 2013]
Chapter 11, “Exceptions”
[Long 2012]
ERR08-J. Do not catch
NullPointerException
or any of its ancestors
43.
Use
a
try
-with-resources
statement
to
safely
handle
closeable
resources
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
java.io.Closeable
interface.
Using the
try
-with-resources statement prevents 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 im-
portant exception when a resource is closed.
Use of the
try
-with-resources statement is also illustrated in
The CERT
®
Oracle
®
Se-
and “FIO04-J. Close resources when they are no longer needed.”
Noncompliant Code Example
This noncompliant code example uses an ordinary
try-catch-finally
block in an at-
tempt to close two resources.