Try with Resources statement in Java
The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it.
The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it.
public static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).
Until 1.5 version it is highly recommended to write finally block to close all resources which are open as part of the try block.
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("abc.txt"));
//use br based on our requirements
} < p class = "para" >
catch(IOException e) {
// handling code
}
finally {
if (br != null) br.close();
}
Problems in this approach
The compulsorily, the programmer is required to close all opened resources with increases the complexity of the programming Compulsory we should write finally block explicitly which increases the length of the code and reviews readability. To overcome these problems Sun People introduced "try with resources" in the 1.7 versions.
We can declare one or more resources in a try-with-resources statement. The following example retrieves the names of the files packaged in the zip file zip file name and creates a text file that contains the names of these files.
public static void writeToFileZipFileContents(String zipFileName, String outputFileName)
throws java.io.IOException {
java.nio.charset.Charset charset = java.nio.charset.StandardCharsets.US_ASCII;
java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName);
// Open zip file and create output file with
// try-with-resources statement
try (
java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)) {
// Enumerate each entry
for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) {
// Get the entry name and write it to the output file
String newLine = System.getProperty("line.separator");
String zipEntryName = ((java.util.zip.ZipEntry) entries.nextElement()).getName() + newLine;
writer.write(zipEntryName, 0, zipEntryName.length());
}
}
}
In this example, the try-with-resources statement contains two declarations that are separated by a semicolon: ZipFile and BufferedWriter.
When the block of code that directly follows it terminates, either normally or because of an exception, the close methods of the BufferedWriter and ZipFile objects are automatically called in this order. Note that the close methods of resources are called in the opposite order of their creation.
Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.
Suppressed Exceptions
An exception can be thrown from the block of code associated with the try-with-resources statement. In the example writeToFileZipFileContents, an exception can be thrown from the try block, and up to two exceptions can be thrown from the try-with-resources statement when it tries to close the ZipFile and BufferedWriter objects.
If an exception is thrown from the try block and one or more exceptions are thrown from the try-with-resources statement, then those exceptions thrown from the try-with-resources statement are suppressed, and the exception thrown by the block is the one that is thrown by the writeToFileZipFileContents method.
You can retrieve these suppressed exceptions by calling the Throwable.getSuppressed method from the exception thrown by the try block.
Classes That Implement the AutoCloseable or Closeable Interface
The Closeable interface extends the AutoCloseable interface.
The close method of the Closeable interface throws exceptions of type IOException while the close method of the AutoCloseable interface throws exceptions of type Exception. Consequently, subclasses of the AutoCloseable interface can override this behavior of the close method to throw specialized exceptions, such as IOException, or no exception at all.
All resources should be auto closable resources, a resource is said to be auto closable if and only if the corresponding class implements the java.lang.AutoClosable interface either directly or indirectly.
All resource reference variables are implicitly final and hence we can't perform reassignment within the try block.
try (BufferedReader br = new BufferedReader(new FileReader("abc.txt"))); {
br = new BufferedReader(new FileReader("abc.txt"));
}
output: CE: Can 't reassign a value to final variable br
Untill 1.6 version try should be followed by either catch or finally but 1.7 version we can take only try with resource without catch or finally
try(R)
{ //valid
}
Java 9 - Effectively Final Variables
Before Java 9, we only could use new variables inside a try-with-resources block.
try (Scanner scanner = new Scanner(new File("testRead.txt"));
PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) {
// omitted
}
try-with-resources With Multiple Resources
We can use Multiple resources in a try-with-resources block by separating them with a semicolon.
try (Scanner scanner = new Scanner(new File("hello.txt"));
PrintWriter writer = new PrintWriter(new File("welcome.txt"))) {
while (scanner.hasNext()) {
writer.print(scanner.nextLine());
}
}
Advantage of "try with resources"
The resources which are opened as part of the try block will be closed automatically Once the control reaches the end of the try block either normally or abnormally and hence we are not required to close explicitly.
Using try with resources, the complexity of programming will be reduced, it is not required to write finally block explicitly and hence the length of the code will be reduced and readability will be improved.
Post/Questions related to Try with Resources statement in Java
Java try-catch Examples
Try with Resources statement in Java
Checked and Unchecked Exceptions in Java
In this article, we have seen Try with Resources in Java.
0 Comments
Post a Comment