Java try-with-resources

try { // Some code that may generate exception }
catch(Exception ex) { //handle exception }
finally { //close any open resources etc. }
try (resource declaration) { 
// use of the resource
} catch (ExceptionType e1) {
// handle exception
import*;class Main {
public static void main(String[] args) {
String line;
try(BufferedReader br = new BufferedReader(new FileReader(“test.txt”))) {
while ((line = br.readLine()) != null) {
System.out.println(“Line =>”+line);
} catch (IOException e) {
System.out.println(“IOException in try block =>” + e.getMessage());
catch(IOException e) {
System.out.println("Thrown exception=>" + e.getMessage());
Throwable[] suppressedExceptions = e.getSuppressed();
for (int i=0; i<suppressedExceptions.length; i++) {
System.out.println("Suppressed exception=>" + suppressedExceptions[i]);
public User findByFirstName(String firstName){
User user =new User();
try (Connection connection = dataSource.getConnection()) {
PreparedStatement selectStatement = connection.prepareStatement("select * from users where first_name = ?");
selectStatement.setString(1, firstName);
ResultSet rs = selectStatement.executeQuery();
if ( { user = extractUserFromResultSet(rs);}
catch (SQLException se) {

return user;
  1. finally block not required to close the resource
  2. . We can declare more than one resource in the try-with-resources statement by separating them with a semicolon ;
try ( Scanner scanner = new Scanner(new File(“testRead.txt”)); 
PrintWriter writer = new PrintWriter(new File(“testWrite.txt”))) {
while (scanner.hasNext()) {
Scanner scanner = new Scanner(new File(“testRead.txt”));
try (scanner) {
// code




System Administrator and Full stack web developer.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Six Steps to Troubleshooting Tableau Dashboards

Extract-Transform-Load in Elasticsearch and Python

Software engineering applied to machine learning

The Importance of Attending Tech Conferences!!

Swift ADS: Quick Sort

AWS Pricing — Where can you go wrong as a Newbie?

How we pair program on the Digital Service Design Team

Design a high scale logging architecture.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Himanshu Pratap

Himanshu Pratap

System Administrator and Full stack web developer.

More from Medium

Cloud Storage, Java

Need for Abstract Classes and Interfaces in JAVA.

Java Variables