The try-with-resources statement

The try-with-resources statement

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

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

The following example writes a string into a file. It uses an instance of FileOutputStream to write data into the file. FileOutputStream is a resource that must be closed after the program is finished with it. So, in this example, closing of resource is done by itself try.


Try-with-resources Example 1

  1. import java.io.FileOutputStream;
  2. public class TryWithResources {
  3. public static void main(String args[]){
  4.         // Using try-with-resources
  5. try(FileOutputStream fileOutputStream =newFileOutputStream(“/java7-new-features/src/abc.txt”)){
  6. String msg = “Welcome to javaTpoint!”;
  7. byte byteArray[] = msg.getBytes(); //converting string into byte array    
  8. fileOutputStream.write(byteArray);
  9. System.out.println(“Message written to file successfuly!”);
  10. }catch(Exception exception){
  11.        System.out.println(exception);
  12. }
  13. }
  14. }

Output:

Message written to file successfuly!

Output of file

Welcome to javaTpoint!

Try-with-resources Example : Using Multiple Resources

  1. import java.io.DataInputStream;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.InputStream;
  5. public class TryWithResources {
  6. public static void main(String args[]){
  7.         // Using try-with-resources
  8. try(    // Using multiple resources
  9.         FileOutputStream fileOutputStream =new FileOutputStream(“/java7-new-features/src/abc.txt”);
  10.         InputStream input = new FileInputStream(“/java7-new-features/src/abc.txt”)){
  11.         // —————————–Code to write data into file——————————————–//
  12.         String msg = “Welcome to javaTpoint!”;
  13.         byte byteArray[] = msg.getBytes();  // Converting string into byte array    
  14.         fileOutputStream.write(byteArray);  // Writing  data into file
  15.         System.out.println(“————Data written into file————–“);
  16.         System.out.println(msg);
  17.         // —————————–Code to read data from file———————————————//
  18.         // Creating input stream instance
  19.         DataInputStream inst = new DataInputStream(input);
  20.         int data = input.available();
  21.         // Returns an estimate of the number of bytes that can be read from this input stream. 
  22.         byte[] byteArray2 = new byte[data]; //  
  23.         inst.read(byteArray2);
  24.         String str = new String(byteArray2); // passing byte array into String constructor
  25.         System.out.println(“————Data read from file————–“);
  26.         System.out.println(str); // display file data
  27. }catch(Exception exception){
  28.        System.out.println(exception);
  29. }
  30. }
  31. }

Output:

------------Data written into file--------------
Welcome to javaTpoint!
------------Data read from file--------------
Welcome to javaTpoint!

You can use catch and finally blocks with try-with-resources statement just like an ordinary try statement.

Note – In a try-with-resources statement, catch or finally block executes after closing of the declared resources.


Try-with-resources Example: using finally block

  1. import java.io.FileOutputStream;
  2. public class TryWithResources {
  3. public static void main(String args[]){
  4. try(    FileOutputStream fileOutputStream=
  5.   new FileOutputStream(“/home/irfan/scala-workspace/java7-new-features/src/abc.txt”)){
  6.     // —————————–Code to write data into file——————————————–//
  7.         String msg = “Welcome to javaTpoint!”;
  8.         byte byteArray[] = msg.getBytes();  // Converting string into byte array    
  9.         fileOutputStream.write(byteArray);  // Writing  data into file
  10.         System.out.println(“Data written successfully!”);
  11. }catch(Exception exception){
  12.        System.out.println(exception);
  13. }
  14. finally{
  15.        System.out.println(“Finally executes after closing of declared resources.”);
  16. }
  17. }
  18. }

Output:

Data written successfully!
Finally executes after closing of declared resources.

Suppressed Exceptions

If a try block throws an exception and one or more exceptions are thrown by the try-with-resources, the exceptions thrown by try-with-resources are suppressed. In other words, we can say, exceptions which are thrown by try-with-resources are suppressed exceptions.

You can get these exceptions by using the getSuppress() method of Throwable class.

Java added a new constructor and two new methods in Throwable class to deal with suppressed exceptions.

Constructor Description
protected Throwable(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) It constructs a new throwable with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled.

Method Description
public final void addSuppressed(Throwable exception)/td> It appends the specified exception to the exceptions that were suppressed in order to deliver this exception. This method is thread-safe and typically called (automatically and implicitly) by the try-with-resources statement. It throws following exceptions: IllegalArgumentException: if exception is throwable, a throwable cannot suppress itself.NullPointerException: if exception is null.
public final Throwable[] getSuppressed() It returns an array containing all of the exceptions that were suppressed by the try-with-resources statement. If no exceptions were suppressed or suppression is disabled, an empty array is returned.
Next TopicJava Type Inference for Generics

 

java for beginners
java for beginners
java for beginners
CodSir //course // books
...

WikiSir

The try-with-resources statement In Java, the try-with-resources statement is a try statement that declares one or more resources. The resource is as an object that must be closed after finishing the program. The try-with-resources statement ensures that each resource is closed at the end of the statement execution. You can pass any object that implements […]

Tags:

....
...