Java 7 try-with-resources statement


In Java 7 you can write the code from the example above using the try-with-resource construct like this:

Screenshot at May 11 23-48-08

This is the try-with-resources construct. The FileInputStream variable is declared inside the parentheses after the trykeyword. Additionally, a FileInputStream is instantiated and assigned to the variable. When the try block finishes the FileInputStream will be closed automatically. This is possible because FileInputStreamimplements the Java interface java.lang.AutoCloseable. All classes implementing this interface can be used inside the try-with-resources construct. If an exception is thrown both from inside the try-with-resources block, and when the FileInputStream is closed (when close() is called), the exception thrown inside the try block is thrown to the outside world. The exception thrown when the FileInputStream was closed is suppressed. This is opposite of what happens in the example first in this text, using the old style exception handling (closing the resources in the finally block).

Reference: http://examples.javacodegeeks.com/core-java/java-7-try-resources-statement/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s