Introduction:

The try-with-resources statement introduces in Java 7 is a try statement that declares one or more resources.
A resource is an object that must be closed after the program is finished with it.
The try-with-resources statement ensures that each resource is closed at the end of the statement.
Any object that implements java.lang.AutoCloseable interface, which includes all objects which implement java.io.Closeable,can be used as a resource.

see the below sample code:-

try (Scanner scanner= new Scanner(new File("example1.txt"));
     PrintWriter writer=new PrintWriter("example2")){
 } catch (Exception ex) {
}

Note: More than two resources can be added separated by a semicolon.

The below code snippet is without try-with-resource

Statement stmt = null;
try {
  stmt = con.createStatement();
} catch (Exception ignore) {
} finally {
  if (stmt != null) stmt.close()
}

becomes a shorter version using the new syntax

try (Statement stmt = con.createStatement()) {
} catch (Exception ignore) {
}

We can use this feature by following the steps below:-

  1. create a class which is being is used as resource and implement autoclosable interface.
  2. Override the close method and write the logic to close the resource.

A custom resource example with autoclosable

package com.codescrap.thread;

import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;

public class TryWithResource {

	public static void testCustomTryWithResource() {
		try (Resource1 con1 = new Resource1();
				Resource2 con2 = new Resource2()) {
		} catch (Exception e) {}
	}

	public static void testTryWithResource() {
		try (Scanner scanner= new Scanner(new File("example1.txt"));
				PrintWriter writer=new PrintWriter("example2")){
		} catch (Exception e) {}
	}

	
	public static void main(String[] args) {		
		testTryWithResource();
		testCustomTryWithResource();
		
	}
}

class Resource1 implements AutoCloseable {

	public Resource1() {
		System.out.println("Resource1...Default cons");
	}

	@Override
	public void close() throws Exception {
		System.out.println("Resource1..close method called");
	}

}

class Resource2 implements AutoCloseable {
	public Resource2() {
		System.out.println("Resource2...Default cons");
	}

	@Override
	public void close() throws Exception {
		System.out.println("Resource2..close method called");
	}

}


The output for the below program :-
Resource1...Default cons
Resource2...Default cons
Resource2..close method called
Resource1..close method called

Please note in the above example the the connection is closed in the reverse order in which it is initialized.

Note: Try-catch can still have the finally block which will work in traditional way.

Hope this helps. Please drop your questions in the comment box