Try-with-resources statement in Java 7

Java SE 7 introduced a new type of try-catch block called try-with-resource.

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

Prior to Java SE 7, you could use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a pre Java 7 finally block to close resource:
static String readFirstLineFromFileWithFinallyBlock(String path)
                                                     throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }
}

Now, with Java 7 you can achieve the same by using try-with-resources statement:
static String readFirstLineFromFileWithFinallyBlock(String path) {

    try (BufferedReader br = new BufferedReader(new FileReader(path))) {

        return br.readLine();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

Here the BufferedReader will be automatically closed after try catch block exits, regardless of whether the try statement completes normally or abruptly.

0 comments:

Post a Comment