Sunday, September 25, 2011

One of new feature of Java 7 : try with resource statement

This is one of new feature introduced in Java 7. This feature provides user with not to handle resource close connection as it is handled by JVM.
Prior to Java 7, user needs to close every resource connection on program completion. If it is not done then it might result in exception or error scenarios.
In earlier versions of Java, sample code is something like this :

static String readData(String filePath) {
    BufferedReader br = new BufferedReader(new FileReader(filePath));
    try{
        return br.readLine();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }finally {
        if(br != null)
            br.close();
    }
}

But with Java 7, user need not to handle resouce connection close scenario and sample code is something like this :

static String readData(String filePath) {
    try(BufferedReader br = new BufferedReader(new FileReader(filePath))) /*User can put multiple resource statements using semi-colon as delimiter*/{
        return br.readLine();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}


Prior to Java7, Closeable interface is implemented by  classes and classes needs to override close() method for closing stream and releases any system resources.
In Java 7, a new interface is introduced and that is AutoCloseable which is extended by interfaces and implemented by classes for automatically handle closing stream and releasing any system resources if it is no longer required.
Using this new feature, resource connection get closed automatically regardless of whether try statement completes normally or abruptly.

If exception is thrown by try block and finally block, exception thrown by try block is suppressed and exception thrown by finally block is catched in previous versions of Java.
But in case of try with resource statement, if exception is thrown by try block and try with resource then exception thrown by try block is catched and exception thrown by try with resource is suppressed. But if user needs suppressed exception, in Java 7 and later versions user can get these exceptions using getSuppressed() method of Throwable class which is introduced in Java 7.

Note: please feel free to provide your comments, queries and suggestions.

2 comments:

  1. Good article man, you have indeed covered topic quite well. I have also shared my view as Why Automatic Resource management is useful in JDK7 let me know how do you find it.

    ReplyDelete