Java The Language Vs. Java the Platform
New and Noteworthy in JDK7 - Part 2
try-with-resources Statements and AutoCloseable
Another bugbear with the verbosity of Java has always been the try-catch-finally syntax. The new language feature try-with-resources statement allow you to compact this in combination with auto-closable resources. Here, rather than the familiar, try-finally to close a resource, you can “open” the resource within the parenthesis of the try statement (as long as the object implements the AutoCloseable interface) and Java will take care of the close call. For example, Oracle’s documentation shows how
This reduced syntax is interesting as it goes a long way to reducing the noise typical to try blocks. An expanded and all too familiar example might be the common try-try-catch-donothing block such as the following.
Which can be reduced to
Here, the auto-closable resource has taken care of the call to close the stream and in its implementation has kindly taken care of the null check for us too. On the down side, the implementation of close in the FileInputStream has added an IOException to the catch list (more accurately, the Closeable interface which extends AutoCloseable and is implemented by FileInputStream has added the exception). Despite the exception, all in all, this should go some way towards tidying up this kind of resource usage so it gets the thumbs up. Its not clear to me however, why Oracle have chosen to miss-spell the interface names though.
There is a little extra detail which could be troublesome when using try-with-resources and that’s suppressed exceptions. Exceptions thrown from within the close method can be suppressed in favour of exceptions thrown from within the try statement’s block. Lets look a little closer at this.
The above example demonstrates an exception being thrown in the close method but it being suppressed, the actual exception caught by the default exception handler in this case will be RuntimeException. For example,
If we put something together based on a decompiled version of the above, you can see what happens behind the scenes.
The JavaDoc tells us that in these situations two exceptions were logically thrown but because the flow of control can only continue with one exception, the other is suppressed. Supressed exceptions are new in JDK7 and can be retrieved in a similar way a cause can via a “getter” method. I can see this occasionally causing the odd problem as I imagine it will become another less well-known caveat that you’re not going to need to be aware of until it’s too late. To be fair though, it’s likely to be something that will be more of an issue when writing your own AutoCloseable implementations than using Oracle's retrofitted classes.