Java Reference
In-Depth Information
all, but allow it to propagate and have the Java interpreter exit with a stack trace and
an error message.
inally
The finally clause is generally used to clean up after the code in the try clause
(e.g., close files and shut down network connections). The finally clause is useful
because it is guaranteed to be executed if any portion of the try block is executed,
regardless of how the code in the try block completes. In fact, the only way a try
clause can exit without allowing the finally clause to be executed is by invoking
the System.exit() method, which causes the Java interpreter to stop running.
a x
In the normal case, control reaches the end of the try block and then proceeds to
the finally block, which performs any necessary cleanup. If control leaves the try
block because of a return , continue , or break statement, the finally block is exe‐
cuted before control transfers to its new destination.
If an exception occurs in the try block and there is an associated catch block to
handle the exception, control transfers first to the catch block and then to the
finally block. If there is no local catch block to handle the exception, control
transfers first to the finally block, and then propagates up to the nearest contain‐
ing catch clause that can handle the exception.
If a finally block itself transfers control with a return , continue , break , or throw
statement or by calling a method that throws an exception, the pending control
transfer is abandoned, and this new transfer is processed. For example, if a finally
clause throws an exception, that exception replaces any exception that was in the
process of being thrown. If a finally clause issues a return statement, the method
returns normally, even if an exception has been thrown and has not yet been
handled.
try and finally can be used together without exceptions or any catch clauses. In
this case, the finally block is simply cleanup code that is guaranteed to be exe‐
cuted, regardless of any break , continue , or return statements within the try
clause.
The try-with-resources Statement
The standard form of a try block is very general, but there is a common set of cir‐
cumstances that require developers to be very careful when writing catch and
finally blocks. These circumstances are when operating with resources that need
to be cleaned up or closed when no longer needed.
Java (since version 7) provides a very useful mechanism for automatically closing
resources that require cleanup. This is known as try -with-resources, or TWR. We
discuss TWR in detail in “Classic Java I/O” on page 289 —but for completeness, let's
Search WWH ::




Custom Search