×

Java Try Resource

In Java, a try argument that specifies one or more resources is known as a try-with-resources statement. When your program is finished utilizing an object, it must be closed, which is known as a resource. a File resource or even a Socket connection resource, for instance. After the statement execution, the try-with-resources statement makes sure that each resource is closed. If we don't seal the resources, it might be a resource leak as well as the program might use up all of the resources at its disposal.

You can use any object that implements java.lang.AutoCloseable, as a resource.  This includes every object that adheres to java.io.Closeable.

As a result, we no longer need to add a second final block to convey the resources' closure statements. Once the try-catch block has been completed, those resources will be closed.

It is also declared as the try-with-resources statement that declares one or more resources as part of a try statement. An object that needs to be closed after the program is done using it is referred to as a resource. At the conclusion of the statement, the try-with-resources clause makes sure that every resource is closed. everything that complies with Java.lang. You can utilize the resource AutoCloseable, which includes all objects that implement java.io.Closeable.

Syntax

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

Exceptions:

There is a distinction between a try-with-resources block and a try-catch-finally block whenever it comes to exceptions. The function returns an exception thrown in the finally block if an exception is thrown within both the try and finally blocks.

If an exception is raised for try-with-resources in both a try block and a try-with-resources statement, the method returns an exception raised in the try block. We can say that the exceptions thrown by the try-with-resources block are suppressed, or that they are thrown in a suppressed manner.

Let's now talk about both of the scenarios that could happen, which are illustrated as examples below:

Case 1: One resource

Case 2: Multiple  resources

Case 1: One resource

Example program

import java.io.FileOutputStream;    
public class TryWithResources
{    
public static void main(String args[])
{      
try(FileOutputStreamfileOutputStream =newFileOutputStream("/java7-new-features/src/abc.txt")){      
String msg = "Hello world";      
byte byteArray[] = msg.getBytes(); 
fileOutputStream.write(byteArray);  
System.out.println("Message written to file successfuly!");      
}catch(Exception exception){  
System.out.println(exception);  
}      
}      
}    

Output

Message  written to file successfully
Output of file
Hello world

Case 2: Multiple  resources

Example program

import java.io.DataInputStream;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.InputStream;    
public class TryWithResources
{    
public static void main(String args[])
{      
try(
FileOutputStreamfileOutputStream =new FileOutputStream("/java7-new-features/src/abc.txt");  
InputStream input = new FileInputStream("/java7-new-features/src/abc.txt")){
        String msg = "Hello world";      
        byte byteArray[] = msg.getBytes();  
fileOutputStream.write(byteArray);  
System.out.println("Writing data to a file");  
System.out.println(msg);  
DataInputStreaminst = new DataInputStream(input);    
        int data = input.available();    
byte[] byteArray2 = new byte[data];  
inst.read(byteArray2);    
        String str = new String(byteArray2);
System.out.println("reading the data from file");  
System.out.println(str);
}
catch(Exception exception)
{  
System.out.println(exception);  
}     
}      
}  

Output

Writing data to a file 
Hello world
Data read from the file
Hello world 

Using Finally Block

import java.io.FileOutputStream;    
public class TryWithResources
{    
public static void main(String args[])
{      
try(  FileOutputStreamfileOutputStream=  
  new FileOutputStream("/home/irfan/scala-workspace/java7-new-features/src/abc.txt"))
  {  
        String msg = "Hello Wold";      
        byte byteArray[] = msg.getBytes(); 
fileOutputStream.write(byteArray);  
System.out.println("successfully writing the data");  
}catch(Exception exception){  
System.out.println(exception);  
}  
finally{
System.out.println("Finally executes after closing the declared resources.");  
}  
}      
}   

Output

successfully writing the data
Finally executes after closing the declared resources.

Suppressed Exceptions

When a try block raises an exception and a try-with-resources raises one or maybe more exceptions as well, the latter exceptions are silenced. Exceptions that are thrown by try-with-resources are, in other words, suppressed exceptions.

By utilizing the getSuppress() function of the Throwable class, you can obtain these exceptions.

To handle suppressed exceptions, Java adds a new function Object(), and two new methods to the Throwable class.

Constructor

protected Throwable(String message, Throwable cause, booleanenableSuppression, booleanwritableStackTrace)

It creates a brand-new throwable with the cause, suppression, writable stack trace, and detail message parameters that you provide.

Methods

public final void addSuppressed(Throwable exception)/td>

In order to convey this exception, it adds the given exception to the ones that were previously silenced. The try-with-resources statement normally calls this thread-safe procedure (automatically and implicitly). The following exceptions are thrown: IllegalArgumentException: If an exception is throwable, it cannot be suppressed by a throwable. NullPointerException: if the exception is null.

public final Throwable[] getSuppressed()

It gives back an array of all the exceptions that the try-with-resources statement managed to suppress. An empty array is given back if there were no exceptions suppressed or if suppression is not enabled.


Related Topics

Java Boolean equals() method

The equals() method of Java Boolean class returns a Boolean value true if the specified argument is not null and is same as this object, else it returns false. Syntax public boolean...

2 minutes read.

How to Create a Package in Java?

For the most part, how to create a package in Java generally, a package is defined as a collection of relevant or irrelevant items together in a very major way....

7 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Difference between C, C++, java

C Language: C language is a procedure oriented language. It has been invented by Dennis Ritchie in the year 1970. It is one of the computer programming language. The purpose of...

3 minutes read.

Objects and Classes in Java

Objects and Classes in Java Classes and objects are the basic concepts of object-oriented programming. It revolves around the real world entity. In Java, the object is a physical and logical...

5 minutes read.

Java Integer equals() method

The equals() method of Integer class compares the given object to the specified object. Syntax public boolean equals(Object obj) Parameters The parameter ‘obj’ represents the object to be compared with. Overrides The equals() method overrides equals...

1 minute read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

Java Boolean toValue() Method

The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true...

2 minutes read.

Empty Statement in Java

The three sorts of statements in Java are control, expression, and declaration statements. Additionally, another statement is referred to as an empty statement. In this section, we will discuss about...

4 minutes read.

Object class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM mostly generally...

6 minutes read.

Difference between String Tokenizer and split Method in Java

Introduction Today, let us understand the difference between String Tokenizer and Split Method. First, let us learn about the String Tokenizer and Split method individually and then know about their differences String...

7 minutes read.

Convert milliseconds to date in Java

In Java, we frequently need to convert milliseconds into Dates with several formats, including dd MM yyyy and dd MM yyyy HH:mm:ss:SSS Z, among others. The Date class is one of the most...

4 minutes read.

Missing Number in an Arithmetic Progression in Java

Given an array that shows the elements of an orderly arithmetic progression. Find the missing number to complete the succession of elements. Example:  Input: a [ ] = {2 , 4 , 6...

3 minutes read.

Java 8 Consumer Interface in Java

The Consumer Interface is used to implement the functional programming in Java. The Consumer Interface indicates a function that accepts a single input and outputs a result. These functions don’t...

2 minutes read.

Diamond problem in Java

The Diamond Problem in Java is connected to multiple inheritances. It is also referred to as the "deadly diamond dilemma" or even the "deadly diamond of death”. The solution for...

5 minutes read.

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.

How to add 6 Months to the Current Date in Java?

In this tutorial, we will learn how to add 6 months to the local or current date in Java language. We will begin our topic with basic concepts and would...

3 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.