The Wayback Machine - https://web.archive.org/web/20240721230226/https://www.geeksforgeeks.org/try-with-resources-feature-in-java/
Open In App

Try-with-resources Feature in Java

Last Updated : 30 Nov, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

In Java, the Try-with-resources statement is a try statement that declares one or more resources in it. A resource is an object that must be closed once your program is done using it. For example, a File resource or a Socket connection resource.  The try-with-resources statement ensures that each resource is closed at the end of the statement execution. If we don’t close the resources, it may constitute a resource leak and also the program could exhaust the resources available to it.

You can pass any object as a resource that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable.

By this, now we don’t need to add an extra finally block for just passing the closing statements of the resources. The resources will be closed as soon as the try-catch block is executed. 

Syntax: Try-with-resources

try(declare resources here) {
    // use resources
}
catch(FileNotFoundException e) {
    // exception handling
}

Exceptions:

When it comes to exceptions, there is a difference in try-catch-finally block and try-with-resources block. If an exception is thrown in both try block and finally block, the method returns the exception thrown in finally block.

For try-with-resources, if an exception is thrown in a try block and in a try-with-resources statement, then the method returns the exception thrown in the try block. The exceptions thrown by try-with-resources are suppressed, i.e. we can say that try-with-resources block throws suppressed exceptions.

Now, let us discuss both the possible scenarios which are demonstrated below as an example as follows:

  • Case 1: Single resource
  • Case 2: Multiple resources

Example 1: try-with-resources having a single resource

Java




// Java Program for try-with-resources
// having single resource
 
// Importing all input output classes
import java.io.*;
 
// Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Try block to check for exceptions
        try (
 
            // Creating an object of FileOutputStream
            // to write stream or raw data
 
            // Adding resource
            FileOutputStream fos
            = new FileOutputStream("gfgtextfile.txt")) {
 
            // Custom string input
            String text
                = "Hello World. This is my java program";
 
            // Converting string to bytes
            byte arr[] = text.getBytes();
 
            // Text written in the file
            fos.write(arr);
        }
 
        // Catch block to handle exceptions
        catch (Exception e) {
 
            // Display message for the occurred exception
            System.out.println(e);
        }
 
        // Display message for successful execution of
        // program
        System.out.println(
            "Resource are closed and message has been written into the gfgtextfile.txt");
    }
}


 Output: 

Resource are closed and message has been written into the gfgtextfile.txt

Example 2: try-with-resources having multiple resources

Java




// Java program for try-with-resources
// having multiple resources
 
// Importing all input output classes
import java.io.*;
 
// Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Try block to check for exceptions
 
        // Writing data to a file using FileOutputStream
        // by passing input file as a parameter
        try (FileOutputStream fos
             = new FileOutputStream("outputfile.txt");
 
             // Adding resource
 
             // Reading the stream of character from
             BufferedReader br = new BufferedReader(
                 new FileReader("gfgtextfile.txt"))) {
 
            // Declaring a string holding the
            // stream content of the file
            String text;
 
            // Condition check using readLine() method
            // which holds true till there is content
            // in the input file
            while ((text = br.readLine()) != null) {
 
                // Reading from input file passed above
                // using getBytes() method
                byte arr[] = text.getBytes();
 
                // String converted to bytes
                fos.write(arr);
 
                // Copying the content of passed input file
                // 'inputgfgtext' file to outputfile.txt
            }
 
            // Display message when
            // file is successfully copied
            System.out.println(
                "File content copied to another one.");
        }
 
        // Catch block to handle generic exceptions
        catch (Exception e) {
 
            // Display the exception on the
            // console window
            System.out.println(e);
        }
 
        // Display message for successful execution of the
        // program
        System.out.println(
            "Resource are closed and message has been written into the gfgtextfile.txt");
    }
}


Output: 

File content copied to another one.
Resource are closed and message has been written into the gfgtextfile.txt

 



Similar Reads

Java SE 9 : Improved try-with-resources statements
In java 7 or 8 if a resource is already declared outside the try-with-resources statement, we should re-refer it with local variable. That means we have to declare a new variable in try block. Let us look at the code explaining above argument : // Java code illustrating try-with-resource import java.io.*; class Gfg { public static void main(String
2 min read
Java Try Catch Block
In Java exception is an "unwanted or unexpected event", that occurs during the execution of the program. When an exception occurs, the execution of the program gets terminated. To avoid these termination conditions we can use try catch block in Java. In this article, we will learn about Try, catch, throw, and throws in Java. Why Does an Exception o
4 min read
Automatic Resource Management in Java ( try with resource statements )
Java provides a feature to make the code more robust and to cut down the lines of code. This feature is known as Automatic Resource Management(ARM) using try-with-resources from Java 7 onwards. The try-with-resources statement is a try statement that declares one or more resources. This statement ensures that each resource is closed at the end of t
5 min read
Flow control in try catch finally in Java
In this article, we'll explore all the possible combinations of try-catch-finally which may happen whenever an exception is raised and how the control flow occurs in each of the given cases. Control flow in try-catch clause OR try-catch-finally clause Case 1: Exception occurs in try block and handled in catch blockCase 2: Exception occurs in try-bl
6 min read
Output of Java Programs | Set 41 (try-catch)
Prerequisite : try-catch, Exception Handling1. What will be the output of the following program? Java Code class Geeks { public static void main(String[] args) { try { System.out.println(1/0); } catch(ArithmeticException e) { System.out.println(e.getMessage()); } } } Options: 1. java.lang.ArithmeticExcetion 2. / by zero 3. java.lang.ArithmeticExcet
3 min read
10 Most Popular Java Frameworks That You Must Try
In today's technology-driven world, we all can see how frequently tech advancements are coming into existence and subsequently how old tools & technologies are becoming obsolete and uncompetitive. But the case is not the same with every single technology as JAVA is one of those few technologies out there that has been enjoying a strong position
9 min read
Nested try blocks in Exception Handling in Java
In Java , we can use a try block within a try block. Each time a try statement is entered, the context of that exception is pushed onto a stack. Given below is an example of a nested try. In this example, the inner try block (or try-block2) is used to handle ArithmeticException, i.e., division by zero. After that, the outer try block (or try-block)
3 min read
HTTP/2 Client feature of Java 9 with Example
HTTP/2 Client: HTTP/2 client is one of the feature of JDK 9. HTTP/2 is the newest version of the HTTP Protocol. By the help of HTTP/2 client, from the Java application, we can send the HTTP request and we can process the HTTP response. Before JDK 9, To send HTTP request and to process the HTTP response we are using HttpURLConnection class. Now you
6 min read
How to Clear or Release Audio Resources in Android?
As the memory consumption in Android is prioritized more, if the Application is using the Mediaplayer API, most of the memory resources are allocated. The developer needs to take care when the Mediaplayer instance is no longer needed or after completion of playing the media resource file. So in this article, it's been discussed how the media player
8 min read
Serve Static Resources With Spring
It's essential to know about static resources, which are the resources that do not change frequently on a web page. To serve these static resources, Spring Boot comes with an inbuilt class called ResourceHttpRequestHandler in conjunction with the ResourceHandlerRegistry class. You can keep these static resources under specific paths like '/public',
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg