Java Try With Resources

The Java try with resources construct automatically close resources like a Java InputStream or a JDBC Connection.

The resources we declare in the try block should extend the java.lang.AutoCloseable class.

try(open resources , one or more resources like JDBC, IO etc)
{
        //...
}

It looks like a Java Constructor to initializes the newly created object before it is used.

/*
try()
{
}
*/
try (BufferedReader br =
 new BufferedReader(new FileReader(path))) 
{
        return br.readLine();
}

Support for try-with-resources – introduced in Java 7 – allows us to declare resources to be used in a try block with the assurance that the resources will be closed when after the execution of that block.

Before Java 7 code style:

Connection con = null;
Statement stmt = null;
ResultSet rs = null;

try {
   con = DriverManager.getConnection(mysqlUrl, "root", "password");
   stmt = con.createStatement();
   rs = stmt.executeQuery("select * from my_table");
} catch (SQLException e) {
   e.printStackTrace();
} finally {
   try {
      rs.close();
      stmt.close();
      con.close();
   } catch(SQLException e) {
      e.printStackTrace();
   }
}

Java 7+ code style:

//Registering the Driver
try(Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
 Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from my_table"); ) 
{  
    //Retrieving the data      
} catch (SQLException e) {
    e.printStackTrace();
}