Java Reference
In-Depth Information
sources
statement (for a full list, see implementers of the
java.lang.AutoCloseable
interface). Also, third-party implementers can create
resources that will work with the
try-with-resources
statements by implement-
ing the
AutoCloseable
interface.
The syntax for the
try-with-resources
statement involves the
try
keyword, followed by an opening parenthesis and then followed by all the resource de-
clarations that you want to have released in the event of an exception or when the block
completes, and ending with a closing parenthesis. Note that if you try to declare a re-
source/variable that doesn't implement the
AutoCloseable
interface, you will re-
ceive a compiler error. After the closing parenthesis, the syntax of the
try
/
catch
block is the same as a normal block.
The main advantage of the
try-with-resources
feature is that it allows a
cleaner release of resources. Usually when acquiring a resource, there are a lot of inter-
dependencies (creating file handlers, which are wrapped in output streams, which are
wrapped in buffered streams). Properly closing and disposing of these resources in ex-
ceptional conditions requires checking the status of each dependent resource and care-
fully disposing of it, and doing so requires that you write a lot of code. By contrast, the
try-with-resources
construct allows the JVM to take care of proper disposal of
resources, even in exceptional conditions.
Note
A
try-with-resources
block will always close the defined resources,
even if no exceptions were thrown.
9-7. Creating an Exception Class
Problem
You want to create a new type of exception that can be used to indicate a particular
event.
Solution 1
Create a class that extends
java.lang.RuntimeException
to create an excep-
tion class that can be thrown at any time. In the following code, a class identified by