You are currently viewing Try-with-resources in java with Example

Try-with-resources in java with Example

In this tutorial, you will learn about Java try-with-resources, Suppressed Exceptions, Retrieving Suppressed Exceptions, and the Advantages of using try-with resources with an example.

What is Java try-with-resources?

A try statement that declares one or more resources is known as a try-with-resources statement. A resource is an object that must be closed once the program has completed its work with it. The try-with-resources statement ensures that at the end of the statement, each resource is closed. Any object that conforms to the java.lang.

At the end of the statement, the try-with-resources statement automatically closes all resources. A resource is a program object that must be closed at the end of the program.

In Java, a try statement that declares one or more resources is known as a try-with-resources statement. The resource is represented as an object that must be closed once the program is completed. The try-with-resources statement ensures that at the end of the statement execution, each resource is closed.

Its syntax is as follows:

try (resource declaration) {
// use of the resource
} catch (ExceptionType e1) {
// catch block
}

As can be seen from the syntax above, we declare the try-with-resources statement by,

  • Within the try clause, declare and instantiate the resource.
  • specifying and dealing with any exceptions that may be thrown while closing the resource

Let’s look at an example that uses the try-with-resources statement.

Example: try-with-resources

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());
    }
  }
}

Output: if the test.txt file is not found.

IOException in try-with-resources block: test.txt (No such file or directory)

Output: if the test.txt file is found.

Entering try-with-resources block
Line: test line

In this example, we use a BufferedReader instance to read data from the test.txt file.

  • Declaring and instantiating the BufferedReader within the try-with-resources statement guarantees that its instance is closed regardless of whether the try statement succeeds or fails.
  • If an exception arises, it can be handled using exception handling blocks or the throws keyword.

Suppressed Exceptions

Exceptions can be thrown from the try-with-resources statement in the preceding example when:

  • The file test.txt could not be found.
  • The BufferedReader object is being closed.
  • As a file read can fail for a variety of reasons at any time, an exception can be thrown from the try block.

If exceptions are thrown from both the try block and the try-with-resources statement, the try block exception is thrown and the try-with-resources statement exception is suppressed.

If a try block throws an exception and the try-with-resources throws one or more exceptions, the exceptions thrown by the try-with-resources are suppressed. To put it another way, exceptions thrown by try-with-resources are suppressed exceptions.

  • These exceptions can be obtained by calling the Throwable class’s getSuppress() method.
  • To deal with suppressed exceptions, Java added 2 new methods to the Throwable class.
MethodDescription
public final void addSuppressed(Throwable exception)/td>It appends the specified exception to the exceptions that were suppressed so that this exception could be delivered. This thread-safe method is typically called (automatically and implicitly) by the try-with-resources statement. The following exceptions are thrown: IllegalArgumentException: A throwable cannot suppress itself if the exception is throwable. NullPointerException: if the exception is null.
public final Throwable[] getSuppressed()It returns an array containing all of the exceptions that the try-with-resources statement suppressed. An empty array is returned if no exceptions were suppressed or if suppression is disabled.

Retrieving Suppressed Exceptions

The suppressed exceptions can be retrieved in Java 7 and later by calling the Throwable method. The method getSuppressed() is derived from the exception thrown by the try block.

This method returns an array of all exceptions that have been suppressed. In the catch block, we get the suppressed exceptions.

catch(IOException e) {
System.out.println(“Thrown exception=>” + e.getMessage());
Throwable[] suppressedExceptions = e.getSuppressed();
for (int i=0; i” + suppressedExceptions[i]);
}
}

Advantages of using try-with-resources

The following are the benefits of utilizing try-with-resources:

1: Finally, there is no need to close the resource.
Prior to Java 7, we had to use the finally block to ensure that the resource was closed to avoid resource leaks.

Here’s a program that works in the same way as an example: In this program, however, we used the finally block to close resources.

Example: Close resource using finally block.

class Main {
  public static void main(String[] args) {
    BufferedReader br = null;
    String line;

    try {
      System.out.println("Entering try block");
      b = new BufferedReader(new FileReader("test.txt"));
      while ((line = b.readLine()) != null) {
        System.out.println("Line =>"+line);
      }
    } catch (IOException e) {
      System.out.println("IOException in try block: " + e.getMessage());
    } finally {
      System.out.println("Entering finally block: ");
      try {
        if (b != null) {
          br.close();
        }
      } catch (IOException e) {
        System.out.println("IOException in finally block:"+e.getMessage());
      }

    }
  }
}

Output

Entering try block:
Line: line from test.txt file
Entering finally block:

  • As we can see from the preceding example, using a finally block to clean up resources complicates the code.
  • Have you noticed the try…catch block in the finally block? This is due to the fact that an IOException may occur while closing the BufferedReader instance within this finally block, and it is also caught and handled.
  • The try-with-resources statement manages resources automatically. We do not need to explicitly close the resources because the JVM does so automatically. This improves the readability and ease of writing of the code.

2: try-with-resources with multiple resources

In the try-with-resources statement, we can declare multiple resources by separating them with a semicolon( ; ).

Example : try with multiple resources

class Main {
  public static void main(String[] args) throws IOException{
    try (Scanner scanner = new Scanner(new File("testRead.txt")); 
      PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) {
      while (scanner.hasNext()) {
        writer.print(scanner.nextLine());
      }
    }
  }
}
  • If this program runs without throwing any errors, the Scanner object reads a line from the testRead.txt file and writes it to a new testWrite.txt file.
  • The try-with-resources statement closes resources in reverse order when multiple declarations are made. In this example, the PrintWriter object is closed first, followed by the Scanner object.

try with resources in java, try with resources example in java, try with resources in java example, how to use try with resources in java, try with resources in java 7 example, difference between try block and try-with-resource in java,,try with resources in java, try with resources example in java, try with resources in java example , how to use try with resources in java, try with resources in java 7 example, difference between try block and try-with-resource in java,,try with resources in java, try with resources example in java, try with resources in java example , how to use try with resources in java, try with resources in java 7 example, difference between try block and try-with-resource in java,

Java 9 try-with-resources enhancement

The try-with-resources statement is restricted in Java 7. Within its block, the resource must be declared locally.

try (Scanner scanner = new Scanner(new File(“testRead.txt”))) {
// code
}

In Java 7, declaring the resource outside the block would have resulted in an error message.

Scanner scanner = new Scanner(new File(“testRead.txt”));
try (scanner) {
// code
}

To address this issue, Java 9 enhanced the try-with-resources statement so that the resource reference can be used even if it is not declared locally. The code above will now run without any compilation errors.

You may like:

Java Exception with Example

Java Exception Handling with Example

Java enum with Example

Java enum Constructor with Example

Java Inheritance with Example | Types of inheritance

Java final Keyword with Example

Not Equal Example in Java

Java Polymorphism with Example

Singleton Class in Java with Implementation and Example

Java Nested and Inner Class with Example

Hope this article will guide you to recognize all about Java try-with-resources with Examples that you needed and still if you have any problem or queries regarding this, post them in the comments section and we will be glad to assist you.

This Post Has 2 Comments

Leave a Reply