try with resource improvement

Java try with resource was a great feature and was first introduced in Java 7. This helps to manage the resource and close them automatically when they are no longer in use. Java 9, making some enhancement in try with resource, So that it will be more readable. In this post, we will see how it works in java 7 and java 8. What does improve with java 9?

If you are not familiar with the try with resource, please read in from here.

try with resource

What is Try-With-Resources?

This statement was first introduced in Java 7 to provide better exception handling. Before java 7, we wrote redundant code to handle the exceptions. It provides some advantages:

1. Try with resources that automatically close the resources like files, database connection, etc. Here resource is an object which should be closed once it is no more required. Before java 7 Developer has to write a lot of redundant and ugly code. But after java 7 there is no need to close them explicitly and it prevents memory leaks.
2. As we said it removes the redundant code, so it makes the code more readable.

3. We don’t need to place null checks.

How do we use try with the resource in java 7?

Let’s see how we used it in java 7.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;  
public class TryWithResourceExample 
{  
    public static void main(String[] args) throws FileNotFoundException {  
        try(FileOutputStream fileOutputStream = new FileOutputStream("JavaGoal.txt"))
        { 
             //We are writing this string in the output file using FileOutputStream
             String mystring = "Hi, This is JavaGoal website file"; 
             
             //Converting the given string in bytes
             byte bytes[] = mystring.getBytes();       
             
             //Writing the bytes into the file
             fileOutputStream.write(bytes);      
             
             //Displaying success message after the successful write operation
             System.out.println("File has written successfully");           
        }
        catch(Exception e) 
        {  
            System.out.println(e);  
        }         
    }  
}

Output: File has written successfully

Problem with the Try-With-Resources in Java 7

But the problem comes when the resource is declared outside the try statement. If we use the resource in the try statement, then it will compilation error. Let’s take an example to understand this.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;  
public class TryWithResourceExample 
{  
    public static void main(String[] args) throws FileNotFoundException 
    {  
    	FileOutputStream fileOutputStream = new FileOutputStream("JavaGoal.txt");
        try(fileOutputStream)
        { 
             //We are writing this string in the output file using FileOutputStream
             String mystring = "Hi, This is JavaGoal website file"; 
             
             //Converting the given string in bytes
             byte bytes[] = mystring.getBytes();       
             
             //Writing the bytes into the file
             fileOutputStream.write(bytes);      
             
             //Displaying success message after the successful write operation
             System.out.println("File has written successfully");           
        }
        catch(Exception e) 
        {  
            System.out.println(e);  
        }         
    }  
}

Output: File has written successfully

If the resource is already declared outside the try-with-resources statement, then we have to assign it to a local variable and then used it in braces of try. To achieve this, we create a local variable as you can see below example:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;  
public class TryWithResourceExample 
{  
    public static void main(String[] args) throws FileNotFoundException 
    {  
    	FileOutputStream fileOutputStream = new FileOutputStream("JavaGoal.txt");
        try(FileOutputStream fileOutputStream1 = fileOutputStream)
        { 
             //We are writing this string in the output file using FileOutputStream
             String mystring = "Hi, This is JavaGoal website file"; 
             
             //Converting the given string in bytes
             byte bytes[] = mystring.getBytes();       
             
             //Writing the bytes into the file
             fileOutputStream.write(bytes);      
             
             //Displaying success message after the successful write operation
             System.out.println("File has written successfully");           
        }
        catch(Exception e) 
        {  
            System.out.println(e);  
        }         
    }  
}

Output: File has written successfully

Java 9 – Try-With-Resources Enhancements

We have discussed the problem in java 7 and java 8 in the above section. But in java 9, we do not need to declare a local variable if the resource is declared outside. In Java 9, the above code runs perfectly fine.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;  
public class TryWithResourceExample 
{  
    public static void main(String[] args) throws FileNotFoundException 
    {  
    	FileOutputStream fileOutputStream = new FileOutputStream("JavaGoal.txt");
        try(fileOutputStream)
        { 
             //We are writing this string in the output file using FileOutputStream
             String mystring = "Hi, This is JavaGoal website file"; 
             
             //Converting the given string in bytes
             byte bytes[] = mystring.getBytes();       
             
             //Writing the bytes into the file
             fileOutputStream.write(bytes);      
             
             //Displaying success message after the successful write operation
             System.out.println("File has written successfully");           
        }
        catch(Exception e) 
        {  
            System.out.println(e);  
        }         
    }  
}

Output: File has written successfully

5 thoughts on “try with resource improvement”

  1. I think the best would be in compile time the Java intercept all AutoClosable created instances and add to the finally block, the language should be clean and the compiler should hide as much complexide as possible from the developer.

Leave a Comment