Try with resource
Try-with-resources in Java 7 is a new way of exception handling which makes it easier to automatically close resources that are used within a try-catch block.
A resource is an object that must be closed after using it.
Example : A file resource for file IO operations, JDBC resource for database connection etc.
Before this feature introduced in Java 7, there was no auto resource management in java and we had to explicitly close the resource after using the resource.
Generally, we do that in the finally block of a try-catch statement.
This approach was causing lot of memory leaks and performance hit when we forgot to close the resource.
Let’s look at the below example
- private static void readFile() throws IOException {
- InputStream input = null;
- try {
- input = new FileInputStream("sample.txt");
- int data = input.read();
- while(data != -1){
- System.out.print((char) data);
- data = input.read();
- }
- } finally {
- if(input != null){
- input.close();
- }
- }
- }
private static void readFile() throws IOException { InputStream input = null; try { input = new FileInputStream("sample.txt"); int data = input.read(); while(data != -1){ System.out.print((char) data); data = input.read(); } } finally { if(input != null){ input.close(); } } }
In the above program, we can see that exception might be thrown in try block in few places like while opening and reading the file
We have used finally block to close resources, it will make sure that code will always be executed no matter exception occurs or not.
If an exception is thrown in the try block then finally block will be executed to close the resource.
What if an exception occurs in finally block while closing the resource?
The exception thrown from the finally block would be propagated to the caller, even though the exception thrown from the try block is more relevant to propagate.
This will kill the actual root cause of exception and throw other exception from finally block.
Let’s do the same in Java 7 try with resource
In Java 7 we can write the above code using try-with-resource construct like this:
- private static void readFileJava7() throws IOException {
- try(FileInputStream input = new FileInputStream("file.txt")) {
- int data = input.read();
- while(data != -1){
- System.out.print((char) data);
- data = input.read();
- }
- }
- }
private static void readFileJava7() throws IOException { try(FileInputStream input = new FileInputStream("file.txt")) { int data = input.read(); while(data != -1){ System.out.print((char) data); data = input.read(); } } }
We can see that the way try block is started, try(FileInputStream input = new FileInputStream("file.txt")) { This way of writing “try” is called try-with-resources
The FileInputStream variable is instantiated and assigned to the variable inside try parenthesis
When the try block completes execution, the FileInputStream will be closed automatically.
This is possible because FileInputStream implements the Java interface java.lang.AutoCloseable.
All classes implementing this interface can be used inside the try-with-resources construct and it will be closed automatically by Java.
So this way, we don’t even need to write finally block to close the resource.
Even if we forget to close resources, Java takes care of it.
We can also use multiple resources within try as below
- private static void readFileJava7() throws IOException {
- try( FileInputStream input = new FileInputStream("file.txt");
- BufferedInputStream bufferedInputStream = new BufferedInputStream(input)
- )
- {
- int data = bufferedInputStream.read();
- while(data != -1){
- System.out.print((char) data);
- data = bufferedInputStream.read();
- }
- }
- }
private static void readFileJava7() throws IOException { try( FileInputStream input = new FileInputStream("file.txt"); BufferedInputStream bufferedInputStream = new BufferedInputStream(input) ) { int data = bufferedInputStream.read(); while(data != -1){ System.out.print((char) data); data = bufferedInputStream.read(); } } }
The above program creates 2 resources inside the parentheses after the try keyword.
1. FileInputStream
2. BufferedInputStream.
Both of these resources will be closed automatically when try block completes execution.
Note :
The resources will be closed in reverse order of the order in which they are created inside the try parentheses. So in above example, First the BufferedInputStream will be closed, then the FileInputStream will be closed.