×

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

String Declaration in Java

A string is a group of characters. In Java, the string can be treated as both class and datatype. In Java programming, the String class have many advantages. Everything in...

3 minutes 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.

Basic Terms in Multithreading

To understand the terms of multithreading, we must have knowledge about concurrency, processes, and threads. Concurrency The concurrency stands for performing multiple tasks at the same time. In the process communication, the operating system permits the process...

8 minutes read.

Implementing Queue Using Array in Java

We can implement queue by using array in Java. The queue is a linear data structure, and the array is one of the simplest data structures. Before implementing a queue...

4 minutes read.

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully...

6 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Convert JSON to Map in Java

JACKSON and GSON libraries are two extremely capable JSON-related libraries offered by Java. To efficiently work with the returned JSON data, we frequently need to convert JSON responses into a...

6 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

Math fma () method in java

In java, the Math module constitutes of fma () Method in it. This method can be accessed in two ways which can be differentiated by the parameters which are given...

4 minutes read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.

Bouncy Number in Java

We will define bouncy numbers in this section and write Java programmes to determine whether a specific number is bouncy. Java coding exams and academic assignments usually inquire about the...

3 minutes read.

Swapping Program in Java

Swapping Program in Java The swapping program in Java is used to interchange the values of the two variables. For example, if X = 12 and Y = 24, then the...

4 minutes read.

Java Map Example

In Java, the Map is an interface that is used mainly to denote key and value pairs. The central concept and theme of this mapping in the java collection framework...

4 minutes read.

Method and Block Synchronization in Java

The Synchronization is performed in multi-threading concept. The multi-threading is a concept of parallel running of a program for the execution. In the multi-threading concept, the threads are run by...

3 minutes read.

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

2 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

Hollow Diamond Pattern in Java

Why are patterns important? Programmers frequently create Java pattern programs to practice coding and ace interviews. Interviewers frequently test candidates' logical reasoning and implementation by asking about pattern programs. Hollow Diamond Pattern The...

7 minutes read.

Functional Interface in Java 8

A brief introduction to Interface in Java: Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or...

11 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.

Java SHA256

Definition: In cryptography, SHA is a hash function that takes 20 bytes of input and produces an approximate 40-digit hexadecimal integer as the hash result. Class for Message Digest: Java's MessageDigest Class,...

2 minutes read.