Java Reference
In-Depth Information
In the event of an exception, you need to ensure that any resources used within a
try / catch block are released.
Solution
Make use of the Automatic Resource Management (ARM) feature, which can be speci-
fied with a try - with - resources statement. When using a try - with - re-
sources statement, any resources that are specified within the try clause are auto-
matically released when the block terminates. In the following code, the FileOut-
putStream , BufferedOutputStream , and DataOutputStream resources
are automatically handled by the try - with - resources block.
try (
FileOutputStream fos = new
FileOutputStream("out.log");
BufferedOutputStream bos = new
BufferedOutputStream(fos);
DataOutputStream dos = new DataOutputStream(bos)
) {
dos.writeUTF("This is being written");
} catch (Exception e) {
System.out.println("Some bad exception happened ");
}
How It Works
In most cases, you want to cleanly close/dispose of resources that are acquired within a
try / catch block after the block execution is complete. If a program does not close/
dispose of its resources or does so improperly, the resources could be acquired indefin-
itely, causing issues such as memory leaks to occur. Most resources are limited (file
handles or database connections), and as such will cause performance degradation (and
more exceptions to be thrown). To avoid these situations, Java provides a way of auto-
matically releasing resources when an exception occurs within a try / catch block.
By declaring a try-with-resources block, the resource on which the try block
was checked will be closed if there is an exception thrown within the block. Most of
the resources that are built into Java will work properly within a try-with-re-
Search WWH ::




Custom Search