Try
with Resource management:
In the previous post we are learning what is exception and how to handle the How to handle exception in java.
The
try
-with-resourcesstatement is a
try
statementthat declares one or more resources. A resource is an object that must
be closed after the program is finished with it. The
try
-with-resources statement ensuresthat each resource is closed at the end of the statement. Any object that
implements
java.lang.AutoCloseable
,which includes all objects which implement
java.io.Closeable
,can be used as a resource.
The following example reads the first line from a file. It uses an instance
of
BufferedReader
to readdata from the file.
BufferedReader
is a resource that must be closed after the program is finished with it:
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
In this example, the resource declared in the
try
-with-resources statement is a BufferedReader
. The declarationstatement appears within parentheses immediately after the
try
keyword. The class BufferedReader
, in Java SE 7 and later,implements the interface
java.lang.AutoCloseable
.Because the
BufferedReader
instance is declared in a
try
-with-resourcestatement, it will be closed regardless of whether the
try
statement completes normally orabruptly (as a result of the method
BufferedReader.readLine
throwing an
IOException
).
Program Snip1:
FileInputStream fis = new FileInputStream(...);
try {
// ... use stream
} catch(IOException e) {
// handle exception
} finally {
try {
if(fis != null) {
fis.close();
}
} catch(IOException e) {
// handle another possible exception
}
}
Program Snip2:
try (FileInputStream fis = new FileInputStream (...)){
// ... use stream
} catch(IOException e) {
// handle exception
}
See the difference between these two
program snips in the second program snip try followed with braces and in program snip1 don’t
have.
In this the resource is an object once the usage of the object
is done it is automatically closed. For example in data base connection,
connection is automatically closed.
See the below Example:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TryWithARM {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("C:\\try.txt"))) {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Advantages of Automatic Resource Management:
More readable and flexible.
Reduce the code.
No need to write finally block because resources are managed in try().
Multiple resources are handled by using semicolon in try catch.
Resources are managed automatically.
Tags
Computer Science