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.