Try-with-resources Statement in Java 7

Java 7 introduces many new features to the java programming language. One of the useful new features added is “try-with-resources” statement.

The 'try-with-resources' statement helps developers to overcome the tedious task of closing the resources that have been used in the program. A resource is basically an object that must be closed after the program has finished with its task.


The Traditional try…catch Statement

To understand try-with-resources better, we will start with the traditional try…catch statement. Let’s take an example of JDBC code for querying a database. Consider the code below where we query a database table called “EMPLOYEE” to get the employee name and salary.

Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String  query = "select emp_name, salary from employee";
try {
    conn = dataSource.getConnection();
    stmt = conn.createStatement();
    rs = stmt.executeQuery(stmt);
    if (rs.next()) {
        String name = employee.setName(rs.getString("emp_name"));
        int salary= employee.setSalary(rs.getInteger("salary"));
        System.out.println(“Employee Name: ”+name + “ Salary: ”+salary);
    }
} catch (SQLException e) {} 
finally {
    if(rs != null) {
        try {
            rs.close();
        } catch(SQLException e) {}
    }
    if(stmt != null) {
        try {
            stmt.close();
        } catch(SQLException e) {}
    }
    if(conn != null) {
        try {
            conn.close();
        } catch(SQLException e) {}
    }
}

Here we have used the finally block to ensure that all our resources used in the program are closed regardless of whether or not try statement executes normally.

The new try-with-resources handles this closing of resources automatically for us. It ensures that all the resources that are declared are closed at the end of the statement.


The improved try statement: Try-with-resources

The code below shows the JDBC example written using try-with-resources.

String  query = "select emp_name, salary from employee ";
try(Connection conn = dataSource.getConnection();
    Statement stmt = conn.createStatement();
    ResultSet  rs = stmt.executeQuery(stmt);) {
    if (rs.next()) {
        String name = employee.setName(rs.getString("emp_name"));
        int salary= employee.setSalary(rs.getInteger("salary"));
        System.out.println(“Employee Name: ”+name + “ Salary: ”+salary);
    }
} catch (SQLException e) {} 

We can see that the finally block is gone; the try-with-resources statement will do the entire resource closing task for us.

To close the resources, Java must know what to close. The resources are declared in the try-with-resources statement using paranthesis. The resources declared are marked bold in the above code block.

RELATED ARTICLES

2 ways to Create a Thread in Java

Threads in Java can be created in 2 different ways, extending the Thread class and implementing the Runnable interface. This article explains the two ways with suitable examples.

View Article

4 Different Ways of Creating an Object in Java

Most of us have created object using new operator in Java. Did you know the other ways to create objects in Java. This article talks about 4 different ways of creating objects in Java.

View Article

Using AutoCloseable with 'try-with-resources'

Java 7 added the java.lang.AutoCloseable interface that developers can implement in their custom classes for using them with try-with-resources.

View Article

Chained Exception

Chained exception is a feature introduced with JDK 1.4, which allow developers to associate an exception with another exception.

View Article

Shallow Cloning and Deep Cloning

Cloning an object can happen in two ways Deep and Shallow Cloning. In shallow cloning only object references are copied while in deep copy actual objects are copied to the newly cloned object.

View Article

Exception Handling in Inheritance

There are certain rules that must be followed while throwing exceptions in inheritance and overriding methods. This article discuss about these rules.

View Article

Garbage Collection in Java

Java Garbage Collector is a boon to Java developers; it allows developers to program without worrying about memory management. This article describes the working of Java Garbage Collector in details.

View Article

Understanding static and final in Java

Java provides various modifiers which when used with variables, methods or classes, provides them with special properties. Static and final are are two such modifiers which are used frequently by Ja..

View Article

Understanding Object Cloning

Java provides the clone() method which can be used to create a copy an object. It creates a new memory location and copies the content of the object being cloned into the new location.

View Article

Varargs: Variable Arguments to Methods

Java 5 introduced a new feature called varargs, which allows methods to accept variable number of arguments. They are useful in cases where the number of arguments to be passed to a method is unknown.

View Article