Java Reference
In-Depth Information
finally {
// Let us try to close the resource
try {
if (aRes != null) {
aRes.close(); // Close the resource
}
}
catch(Exception e) {
e.printStackTrace();
}
}
With the new
try-with-resources
construct in Java 7, the above code can be written as
try (AnyResource aRes = create the resource...) {
// Work with the resource here. The resource will be closed automatically.
}
Wow! You were able to write the same logic in just three lines of code using a
try-with-resource
construct
in Java 7, when it used to take sixteen lines of code. The
try-with-resources
construct automatically closes the
resources when the program exits the construct. A
try-with-resource
construct may have one or more
catch
blocks
and/or a
finally
block.
On the surface, the
try-with-resources
construct is as simple as it seems in the above example. However, it
comes with some subtleties that I need to discuss in detail.
You can specify multiple resources in a
try-with-resources
block. Two resources must be separated by a
semicolon. The last resource must not be followed by a semicolon. The following snippet of code shows some usage of
try-with-resources
to use one and multiple resources:
try (AnyResource aRes1 = getResource1()) {
// Use aRes1 here
}
try (AnyResource aRes1 = getResource1();
AnyResource aRes2 = getResource2()) {
// Use aRes1 and aRes2 here
}
The resources that you specify in a
try-with-resources
are implicitly
final
. You can declare the resources
final
, even though it is redundant to do so.
try (final AnyResource aRes1 = getResource1()) {
// Use aRes1 here
}
A resource that you specify in a
try-with-resources
must be of the type
java.lang.AutoCloseable
. Java 7
added the
AutoCloseable
interface, which has a
close()
method. When the program exits the
try-with-resources
block, the
close()
method of all the resources is called automatically. In the case of multiple resources, the
close()
method is called in the reverse order in which the resources are specified.
Consider a
MyResource
class as shown in Listing 9-14. It implements the
AutoCloseable
interface and provides
implementation for the
close()
method. If the
exceptionOnClose
instance variable is set to
true
, its
close()
method
throws a
RuntimeException
. Its
use()
method throws a
RuntimeException
if the
level
is zero or less. Let's use the
MyResource
class to demonstrate various rules in using the
try-with-resources
block.