Try with Resource

  • A try statement that declares one or more resources is the try-with-resources statement. The resource it declares is an object that must be closed after finishing the program.
  • The try-with-resources statement ensures that each resource is closed at the end of the statement execution automatically. The only condition is that the resources should implement the AutoCloseable interface. It happens regardless of whether any exceptions are thrown either when attempting to close the resources or from inside the try-with-resources block.
  • It allows one to declare multiple resources by separating them with a semicolon.
  • If a try block throws an exception and one or more exceptions are thrown by the try-with-resources, the exceptions thrown by try-with-resources are suppressed. So they are known as suppressed exceptions. One can get these exceptions by using the getSuppress() method of Throwable class.
  • The resources that are defined/acquired first in the try with resources statement, will be closed last. In other words, when multiple resources are opened in try-with-resources, it closes them in the reverse order. This is done to avoid any dependency issues. 
  • In addition, this block can have the catch and finally blocks as well which will work in the same way as with a traditional try block.
// Try, Catch, Finally

Scanner scanner = null;
try {
	scanner = new Scanner(new File("test.txt"));
	PrintWriter writer = new PrintWriter(new File("testWrite.txt"));
	while(scanner.hasNext()) {
		writer.print(scanner.nextLine());
		System.out.println(scanner.nextLine());
	}
} catch(FileNotFoundException e){
	e.printStackTrace();
} finally{
	if(scanner != null) {
		scanner.close();
	}
}
//Try with Resources

try (
	Scanner scanner = new Scanner(new File("test.txt"));
	PrintWriter writer = new PrintWriter(new File("testWrite.txt"))
	){
		while(scanner.hasNext()) {
			writer.print(scanner.nextLine());
			System.out.println(scanner.nextLine());
		}
} catch(FileNotFoundException e) {
	e.printStackTrace();
}
Scroll to Top