Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Understanding Try with Resources Concept in Java

[post-views]

 

 

In this lesson, you will learn.

  • Try-with-Resources
  • Example

 

Try-with-Resources

  1. In Java, “try with resources” is a feature that simplifies the management of resources such as files, sockets, and database connections that need to be closed after their operations are completed.
  2. This feature was introduced in Java 7 to handle resource management more safely and efficiently by automatically closing resources, thereby reducing the risk of resource leaks.

 

Important Points!

A stream must be closed when it is no longer needed. Failure to do so can lead to memory leaks and resource starvation.

 

Two Ways to Close a Stream

1. A Traditional Approach to Close a Stream (Before JDK 7)

The first is to call a close( ) function on the stream explicitly.

try {
 // open and access file
} catch( I/O-exception) {
 // ...
} finally {
 // close the file
}

 

2. Using Try-With-Resources (Added in JDK 7)

  • The second approach to closing a stream is to automate the process by using the try-with-resources statement that was added by JDK 7.
  • The try-with-resources statement is an enhanced form of try that has the following form.

 

try (resource-specification) {
 // use the resource
}
catch (ExceptionType e) {
    // handle any exceptions
}

 

Here, resource-specification is a statement or statement that declares and initializes a resource, such as a file or other stream-related resource.

When the try block ends, the resource is automatically released. In the case of a file, this means that the file is automatically closed. Thus, there is no need to call close( ) explicitly.

 

Here are the 3 key points regarding try-with resources example

  1. Resources managed by try-with-resources must be objects of classes that implement AutoCloseable interface
  2. The resource declared in the try is implicitly final.
  3. You can manage more than one resource by separating each declaration by a semicolon.

 

The principal advantage of try-with-resources is that the resource (in this case, a stream) is closed automatically when the try block ends.

 

How Does the Try with Resources Work?

The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable or java.io.Closeable can be used as a resource.

Syntax

try (ResourceType resource = new Resource()) {
    // use the resource
} catch (ExceptionType e) {
    // handle any exceptions
}

After the try block, the resource will be automatically closed, regardless of whether the try block completes normally or abruptly (due to an exception).

This automatic closure eliminates the need for a finally block solely to close the resources, which reduces boilerplate code and improves readability.

 

Example 1: Writing to a File Without Try-With-Resources

package trywithresource;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class TraditionalFileWrite {
    public static void main(String[] args) {
        BufferedWriter br = null;
        try {
        	br = new BufferedWriter(new FileWriter("traditional.txt"));
        	br.write("It is a traditional approach");
        	br.write("Make sure to close resources in the finally block.");
            System.out.println("File writing operation completes..");
        } catch (IOException e) {
            System.err.println("Error occurred: " + e.getMessage());
        } finally {
            if (br != null) {
                try {
                	br.close();
                } catch (IOException e) {
                    System.err.println("Faile to close: " + e.getMessage());
                }
            }
        }
    }
}

 

Output

 

Example 2: Writing to a File Using Try-With-Resources

package trywithresource;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class TryWithResourcesExample {
    public static void main(String[] args) {
        // BufferedWriter is automatically closed at the end of the try block
        try (BufferedWriter br = new BufferedWriter
        		(new FileWriter("with_resources.txt"))) {
            br.write("Hello, this is a test using try-with-resources.n");
            br.write("No need for a finally block to close resources.");
            System.out.println("File writing operation completes..");
        } catch (IOException e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
        // No need for a finally block here
    }
}

 

Output

 

Traditional Method:

  • Code Complexity: Requires manual management of resource closure in a finally block, which adds to the code complexity.
  • Error Handling: Failure to properly close resources in a finally block can lead to resource leaks, especially if the closure itself can throw an exception.
  • Boilerplate Code: More lines of code are required to safely manage resources.

 

Try-With-Resources Method:

  • Code Simplicity: Automatically handles the closing of resources, reducing code complexity.
  • Reliability: Ensures that resources are always closed, even if an exception is thrown, making the code more reliable.
  • Reduced Boilerplate: Less code is needed, making the program easier to read and maintain.

 

In summary, try-with-resources provides a safer and cleaner way to handle resources in Java. It is especially useful in scenarios involving closeable resources like streams, where managing closure and exceptions can become cumbersome with traditional trycatchfinally blocks.

 

 

 

 


 

End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review