Java Reference
In-Depth Information
14.20.3. try -with-resources
A try -with-resources statement is parameterized with variables (known as resources ) that
are initialized before execution of the try block and closed automatically, in the reverse or-
der from which they were initialized, after execution of the try block. catch clauses and a
finally clause are often unnecessary when resources are closed automatically.
TryWithResourcesStatement:
try ResourceSpecification Block Catches opt Finally opt
ResourceSpecification:
( Resources ; opt )
Resources:
Resource
Resource ; Resources
Resource:
VariableModifiers opt Type VariableDeclaratorId = Expression
A ResourceSpecification declares one or more local variables with initializer expressions
to act as resources for the try statement.
A resource declared in a ResourceSpecification is implicitly declared final 4.12.4 ) if it is
not explicitly declared final .
The type of a variable declared in a ResourceSpecification must be a subtype of
AutoCloseable , or a compile-time error occurs.
The scope and shadowing of a variable declared in a ResourceSpecification is specified in
§ 6.3 and § 6.4 .
It is a compile-time error for a ResourceSpecification to declare two variables with the
same name.
Resources are initialized in left-to-right order. If a resource fails to initialize (that is, its ini-
tializer expression throws an exception), then all resources initialized so far by the try -with-
resources statement are closed. If all resources initialize successfully, the try block executes
as normal and then all non-null resources of the try -with-resources statement are closed.
Resources are closed in the reverse order from that in which they were initialized. A re-
source is closed only if it initialized to a non-null value. An exception from the closing
of one resource does not prevent the closing of other resources. Such an exception is sup-
pressed if an exception was thrown previously by an initializer, the try block, or the closing
of a resource.
Search WWH ::




Custom Search