The try-with-resources statement, introduced in Java 7, eliminates the need for a lengthy finally block.
try(resource_name) { //Statements }catch(Exception e) { //Statements }
A resource is an object that must be closed once your program is done using it, like a File resource or JDBC resource for database connection or a Socket connection resource.
Before Java 7, there was no auto resource management and we should explicitly close the resource once our work is done with it. Usually, it was done in the finally block of a try-catch statement.
Java 6
try{ //open resources like File, //Database connection,Sockets etc } catch(FileNotFoundException e) { //Exception handling like //FileNotFoundException,IOException etc } finally { // close resources }Java 7
try(// open resources here) { // use resources } catch(FileNotFoundException e) { // exception handling }
// resources are closed as soon //as try-catch block is executed.
String readFirstLine(String path) throws IOException { BufferedReader br = new BufferedReader(new FileReader(path)); try { return br.readLine(); } finally { if (br != null) br.close(); } }
String readFirstLine(String path) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } }All resource will be freed automatically.
Example 1: try-with-resources statement:
public void readEmployees(Connection con) { String sql = "Select * from Employee"; try ( Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql) ) { //Work with Statement and ResultSet } catch (SQLException e) { e.printStackTrace(); } }
In case of multiple resources, close() method of all the resources is called, and order of calling close() method is reverse of declaration.
System.out.println("About to open a file"); try ( InputStream in = new FileInputStream("missingfile.txt") ) { System.out.println("File open"); int data = in.read(); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); }
Resource in a try-with-resources statement must implement either:
The following code shows how to declare the AutoClosable interface with the close() method:
public interface AutoCloseable { void close() throws Exception; }