×

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

Equidigital in Java

In this section, we will understand what is an equidigital number and how to write Java programs to locate them. It is commonly asked in academic settings and Java coding...

4 minutes read.

Java vs JavaScript

Java Vs JavaScript Java and JavaScript, both play an important role in the field of Computer Technology. Most people think JavaScript is a part of Java. But it is not entirely...

4 minutes read.

Java RMI

What is RMI in Java? A framework for developing distributed Java applications is provided by the RMI (Remote Method Invocation) API. An object can call methods on an object running in...

4 minutes read.

Java Class Name

How to write a class name? The following considerations should be made while writing class names. The name of the current class shouldn't be based on a preset or existing class. Java keywords...

3 minutes read.

Java Int Keyword

Among the primitive data types is the Java int keyword. To declare variables, use this. It can also be used with methods that return values of the integer type. It...

3 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

Java Binary Tree

The non-linear data structure known as a binary tree is a type of tree, and because it stores data in a hierarchical manner, it is mostly utilised for finding and...

7 minutes read.

Java float vs double

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.

Rectangular Numbers in Java

In this tutorial, we will understand the meaning of a rectangular number in Java with the aid of examples, illustrations, and implementations. It is one of the popular coding interview...

3 minutes read.

HashMap Vs HashTable

HashMap HashMap is the basic implementation of the map interface in Java. HashMap stores the data in key and value pairs. Keys are used to access the value of the element. It...

5 minutes read.

Sphenic Number in Java

In this section, we will learn what is a sphenic number is and show you how to write Java programmes to determine if a specific number are sphenic or not....

3 minutes read.

Interleaving string in Java

If the string Str3 contains all of the characters from Str1 and Str2, it is considered interleaving Str1 and Str2. Keep in mind that the order of all characters in...

5 minutes read.

Java Boolean parseBoolean() Method

The parseBoolean() method of Boolean class returns a Boolean value for the specified String argument. It returns true if and only if string’s value is equal to “true”, else it...

1 minute read.

Nth node from the end of the Linked list in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

6 minutes read.

Java Integer numberOfTrailingZeros() method

The numberOfTrailingZeros()  method of Java Integer class returns the total number of zero bits following the lowest-order one-bit in the 2’s complement binary representation of the specified int value. Syntax public static...

1 minute read.

Java Math atan2() Method

The atan2() method of Math class returns an angle theta from the conversion of rectangular coordinates to polar coordinates. Syntax: public static double atan2(double y, double x) Parameters: The parameter ‘y’ represents the ordinate...

3 minutes read.

Java Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

Java Else Keyword

The else statement specifies a section of Java code that will run if an if statement's condition is false.The following conditional statements can be used in Java:To provide a block...

3 minutes read.

Magic Square in Java

A square with numbers is referred to as a magic square. The numbers in a magic square of order n are arranged to ensure that the sum of all of...

4 minutes read.