java 7 try with resources example

Resource:

A resource is an object that must be closed after the program is finished with it. For example a File resource or JDBC resource for database connection.

The try-with-resources statement:

Main concept behind the try-with-resources statement is auto resource management. Before Java 7, there was no auto resource management and we explicitly have to close the resource once our work is done with it.

The try-with-resources statement is a try statement that declares one or more resources. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable.

Syntax:

try(open file or resource here){
 //...
}
//after try block, file will close automatically.

Note:

  • In a try-with-resources statement, catch or finally block executes after closing of the declared resources.
  • In case of multiple resources are opened in try-with-resources, it closes them in the reverse order to avoid any dependency issue.

Java try-with-resources statement example

package com.w3schools;

import java.io.FileInputStream;

public class TryWithResourcesExample {
	public static void main(String args[]){
		try(FileInputStream input = new FileInputStream("D:\\test.txt")) {
	        int data = input.read();
	        while(data != -1){
	            System.out.print((char) data);
	            data = input.read();
	        }
	    } catch (Exception e) {
			e.printStackTrace();
		}  
	}
}

Output

Hello w3schools




Java try with multiple resources example

package com.w3schools;

import java.io.BufferedInputStream;
import java.io.FileInputStream;

public class TryWithResourcesExample {
	public static void main(String args[]){
		try(FileInputStream input = new FileInputStream("D:\\test.txt");
			BufferedInputStream bufferedInput = new BufferedInputStream(input)) {
			int data = bufferedInput.read();
	        while(data != -1){
	            System.out.print((char) data);
	            data = bufferedInput.read();
	        }
	    } catch (Exception e) {
			e.printStackTrace();
		}  
	}
}

Output

Hello w3schools

Java try-with-resources exceptions example

In case of try-catch-finally, if an exception is thrown in both try block and finally block, the method returns the exception thrown in finally block. While in case of try-with-resources, if exception is thrown in try block and in try-with-resources statement, then method returns the exception thrown in try block.

package com.w3schools;

public class TryWithResourcesExample {
	static void normalTryException() throws Exception {
		MyResource mr = null;
		try {
			mr = new MyResource();
			System.out.println("MyResource created in try block");
			if (true)
				throw new Exception("Exception in try");
		} finally {
			if (mr != null)
				mr.close();
		}

	}

	static void tryWithResourceException() throws Exception {
		try (MyResource mr = new MyResource()) {
			System.out.println("MyResource created in try-with-resources");
			if (true)
				throw new Exception("Exception in try");
		}
	}

	static class MyResource implements AutoCloseable {

		@Override
		public void close() throws Exception {
			System.out.println("Closing MyResource");
			throw new Exception("Exception in Closing");
		}

	}
	public static void main(String args[]){
		try {
			tryWithResourceException();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		try {
			normalTryException();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}

Output

MyResource created in try-with-resources
Closing MyResource
Exception in try
MyResource created in try block
Closing MyResource
Exception in Closing