Paul C. Williams

Interfacing Technology & Business
View Paul Williams's profile on LinkedIn

Tuesday, May 13, 2014

Java 1.7 features of note : try-with-resources and suppressed exceptions

In Java 1.7, a new feature called "try-with-resources" was introduced.  This is a specialized "try"/"catch" block that recognizes that you have a "closable" resource that must be closed.  Using this feature will ensure the resource is closed at the end of the statement.

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br = new BufferedReader(new FileReader(path))) {
        return br.readLine();
    } // MAGIC! The resource is closed after this line!

You can create your own resources that can be managed using this method by implementing the "java.lang.AutoClosable" interface (or java.lang.Closable which extends AutoClosable), which has one method: void close()

Add this syntactic sugar to your code to produce tasty and un-polluted closing for all kinds of file or database resources.

Also new in Java 1.7, the Throwable class includes a Throwable[] getSuppressed() method. This method allows a developer to access exceptions that were suppressed by a framework. The Java JRE uses this if there's a suppressed exception as part of the autoclose, but this feature could also be used by frameworks to aggregate exceptions that might have been encountered during batch or aggregate operations.

1 comment: