In this post, we will see about Java try with resources
Statement.
Table of Contents
try with resources
is a feature of Java which was added into Java 7
. It helps to close all the resources declared within try block
. It automatically closes the resources after being used. A resource can be any file or a database connection.For example, if we are working with File handing then after opening a file, it requires to be closed after reading or writing data. In early versions of Java, we have to explicitly close the resource, but from
Java 7
, we don’t need to worry about to close the resources.
What type of resources can be handled automatically?
Java says, any object that implements java.lang.AutoCloseable
interface and java.io.Closeable
interface, can be used as a resource.
Let’s start with examples to understand the topic.
Older approach to close the resources
This is an older approach that we used to handle file related operations.
Notice, we manually closed the resource using close()
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.io.FileOutputStream; public class Main{ public static void main(String[] args){ try { FileOutputStream fileOutputStream =new FileOutputStream("info.txt"); fileOutputStream.write("Java2blog is a technical blog".getBytes()); System.out.println("File is written"); fileOutputStream.close(); // closing resource }catch(Exception e) { System.out.println(e); } } } |
Output:
Java 7 try with resources
The try with resources was introduced with Java 7 and helps to reduce the effort to close the resources manually. Now, we don’ need to use close()
method. See the example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.io.FileOutputStream; public class Main{ public static void main(String[] args){ try (FileOutputStream fileOutputStream = new FileOutputStream("info.txt")){ fileOutputStream.write("Java2blog is a technical blog".getBytes()); System.out.println("File is written"); // fileOutputStream.close(); No need to close manually }catch(Exception e) { System.out.println(e); } } } |
Output:
Syntax
The following is the syntax of try with resources that includes function like parenthesis to collect resources.
1 2 3 4 5 6 7 8 9 10 |
try( // resources ){ // body of try block }catch( // Exception ) { // handler code } |
Note: Prior to Java 7 version, only finally block is used to ensure that a resource is closed properly.
Example
Let’s take one more example of Java try with resources. Here, we are creating database connection and not closing the connection because it will be handled by new try block.
Notice, we used multiple resources inside it that means it can handle multiple resources as well.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Main{ public static void main(String[] args){ try( Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/employee","user_name","user_password"); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("select * from emp"); ) { while(rs.next()){ System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getString(3)); } } catch(Exception e){ System.out.println(e); } } } |
Java 9 Try with resources Improvements
In Java 9, try with resources is improved that allows to declare or create the resources outside the try block. Before Java 9, it was not possible, and compiler generates error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.io.FileNotFoundException; import java.io.FileOutputStream; public class Main{ public static void main(String[] args) throws FileNotFoundException{ FileOutputStream fileOutputStream = new FileOutputStream("info.txt"); // Outside the try block try (fileOutputStream){ fileOutputStream.write("Java2blog is a technical blog".getBytes()); System.out.println("File is written"); }catch(Exception e) { System.out.println(e); } } } |
Output:
See, we declared the resource outside the try with resources and compiler compiles the file successfully, but in case of Java 7 or Java 8, we can not do this.
Finally block with try with resources
Although Java try with resources does resource cleanup tasks automatically but in case, if there is any resource which does not implement AutoCloseable
interface need to be closed in finally block.
In this example, we are using finally block with try with resources.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.io.FileNotFoundException; import java.io.FileOutputStream; public class Main{ public static void main(String[] args) throws FileNotFoundException{ FileOutputStream fileOutputStream = new FileOutputStream("info.txt"); try (fileOutputStream){ fileOutputStream.write("Java2blog is a technical blog".getBytes()); System.out.println("File is written"); }catch(Exception e) { System.out.println(e); } finally { // resource releasing code System.out.println("Finally block is executed"); } } } |
Output:
Finally block is executed
Create Custom AutoCloseable Code
Any class that implements AutoCloseable
interface can be used in try with resources
. Let’s create a class and implements AutoCloseable
interface. This class has some utility methods.
Notice, we did not call close()
method of SetupConnection
class, but it is called implicitly by the compiler. See the example and its output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class SetupConnection implements AutoCloseable{ void configureConnection() { System.out.println("Connection configured."); } void connect() { System.out.println("Connected"); } @Override public void close() throws Exception { System.out.println("Connection is closed."); } } public class Main{ public static void main(String[] args){ SetupConnection con = new SetupConnection(); try (con){ con.configureConnection(); con.connect(); }catch(Exception e) { System.out.println(e); } } } |
Output:
Connected
Connection is closed.
That’s all about Java Try with resources.