Java - Try vs Try-with-Resources

JDK 7 comes with try-with-resources feature which allows automatic closing of resources without explicit finally block leading to minimal code and avoids boilerplate code required for closing of resources.

pre-JDK 7

try {
  // open resources such as input and output streams, db connecctions, sql statements etc.
  // use the resources
}catch() {
  // handle exceptions
}finally {
  // close resources
}

 JDK 7 onwards

try( // open one or more resources ) {
  // write some logic
} catch() {
  // handle exceptions
}
 // no code required , resources will be closed automatically

Compare both the implementations with Examples :

Lets see the examples of both normat try statement and try-with-resources statement.

pre-JDK 7 ( nomral Try statement ) Example

package com.codeforeach.demo;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class NormalTry {
 public static void main(String[] args) {
   BufferedReader br = null;
   try {
     br = new BufferedReader(new FileReader("codeforeach.txt"));
     System.out.println(br.readLine());
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
      if (br != null) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        } } } }
}

 JDK 7 onwards ( try-with-resources statement ) Example

package com.codeforeach.demo;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

class TryWithResources {
  public static void main(String[] args) {
    try (BufferedReader br = new BufferedReader(new FileReader("codeforeach.txt"))) {
      System.out.println(br.readLine());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Resource - Any class which implements AutoCloseable interface. Java 7 onwards, most of the classes including BufferedReader, BufferedWriter etc, implements AutoCloseable .

Custom Resource implementation Example :

Lets now implement some resource which can be used in try-with-resources statement.

class MyCustomResource implements AutoCloseable {
 public void doSomeWork() throws Exception {
   System.out.println("MyCustomResource is created and doing some work");
   throw new Exception("doSomeWork exception");
 }

 @Override
 public void close() throws Exception {
  // write code for closing the resource properly
  System.out.println("MyCustomResource is closed");
  throw new Exception("close exception");
 }
}

Now use the resource in try-with-resource statement.

class TryWithResources {
  public static void main(String[] args) {
    try (MyCustomResource r = new MyCustomResource()) {
      r.doSomeWork();
    } catch (Exception e) {
      // exception from try block
      System.out.println("Exception from try block statement doSomeWork() : " + e.getMessage());
      // exception from resource closing would be suppressed and need to be accessed using getSuppressed() method. 
      System.out.println("Exception from resource close() : " + e.getSuppressed()[0].getMessage());
    }
  }
}
MyCustomResource is created and doing some work
MyCustomResource is closed
Exception from try block statement doSomeWork() : doSomeWork exception
Exception from resource close() : close exception

Here, you can understand the flow of execution by looking at output statements above.

Some points to be noted :
1) Always , resources would be closed immediately after the try block and before catch/finally.
2) Try block exception can be accessed directly through exception object whereas resource closing exception would be suppressed and need to be accessed through the method getSuppressed().

References

https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

 

 

Submit a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

www.000webhost.com