Try-with-resources Feature in Java
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
Please Login to comment...