Java 9 Even More Good – Part 2

We all know try-with-resources feature introduced in java 7 it has released the burden to use finally block to close the connection below is the example

try(Connection connection=getConnection()){



but there was one problem what if you get connection from any other method it may be happen like this

public void doWithConnection(Connection connection) {

try(Connection c=connection){



The variable c is just there because the try-with-resources statement’s syntax required it – the managed resources had to be declared in the statement’s head

But java 9 has resolved this problem below is the solution

public void doWithConnection(Connection connection) {




See the italicized part

you just have to tell the try block the name of the variable the rest of the work to close the actual reference of connection it will do automatically


Leave a Reply

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

You are commenting using your 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