Java try-with-resources

Try with resources

What is try with resources?

Java try-with-resources is a language feature introduced in Java 7 that simplifies the handling of resources such as files, database connections, and network sockets.

It automatically closes the resources when they are no longer needed, even if an exception occurs, reducing the chance of resource leaks and improving code readability.

To understand the more about Java try with resources, Read the Complete Article.

java try-with-resources multiple

  • You can declare and initialize multiple resources within the same try-with-resources statement. To do so, simply separate each resource declaration with a semicolon.

  • Each resource declaration must be a valid expression that creates an object of a class that implements the AutoCloseable interface.

  • The resources are closed in the opposite order in which they are declared. That is, the last resource declared is closed first, and so on.

  • The try-with-resources statement can still include a catch and/or finally block (optional) to handle exceptions and perform cleanup tasks.

  • If an exception occurs during the closing of one of the resources, the exceptions are added to the original exception thrown by the try block and are referred to as “suppressed” exceptions.

Java try with resources

Advantages of using try-with-resources: 

Feature Description
SyntaxThe try-with-resources statement consists of a try block, one or more resource declarations, and a catch and/or finally block (optional).
Suppressed exceptionsTry-with-resources can capture and handle suppressed exceptions that occur during the closing of resources.
Improved readabilityTry-with-resources can improve the readability of the code by making it easier to focus on the main logic of the program.
Cleaner and more concise codeTry-with-resources eliminates the need for explicit finally blocks to close resources, making code cleaner and more concise.
Automatic resource managementThe try-with-resources statement automatically closes resources such as files, network sockets, and database connections when they are no longer needed.

Example 1: Java Try with resources with mutiple resources. 

Run

import java.io.*;

public class Main {
    public static void main(String[] args) {
        try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
             BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                writer.write(line);
                writer.newLine();
            }
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

Output

Error reading file: example.txt (No such file or directory)

Example 2: Java Try with resources 

Run
import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

 
public class Main
{
  
public static void main (String[]args)
  {
    
try (BufferedReader reader =
	  new BufferedReader (new FileReader ("example.txt")))
    {
      
String line = null;
      
while ((line = reader.readLine ()) != null)
	{
	  
System.out.println (line);
	
}
    
}
    catch (IOException e)
    {
      
System.err.println ("Error reading file: " + e.getMessage ());
    
}
  
}

}

Output

Error reading file: example.txt (No such file or directory)

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription