The try-with-resources statementIn Java, the try-with-resources statement is a try statement that declares one or more resources. The resource is as an object that must be closed after finishing the program. The try-with-resources statement ensures that each resource is closed at the end of the statement execution. You can pass any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable. The following example writes a string into a file. It uses an instance of FileOutputStream to write data into the file. FileOutputStream is a resource that must be closed after the program is finished with it. So, in this example, closing of resource is done by itself try. Try-with-resources Example 1Output: Message written to file successfuly! Output of file Welcome to javaTpoint! Try-with-resources Example : Using Multiple ResourcesOutput: ------------Data written into file-------------- Welcome to javaTpoint! ------------Data read from file-------------- Welcome to javaTpoint! You can use catch and finally blocks with try-with-resources statement just like an ordinary try statement. Note - In a try-with-resources statement, catch or finally block executes after closing of the declared resources.Try-with-resources Example: using finally blockOutput: Data written successfully! Finally executes after closing of declared resources. Suppressed ExceptionsIf a try block throws an exception and one or more exceptions are thrown by the try-with-resources, the exceptions thrown by try-with-resources are suppressed. In other words, we can say, exceptions which are thrown by try-with-resources are suppressed exceptions. You can get these exceptions by using the getSuppress() method of Throwable class. Java added a new constructor and two new methods in Throwable class to deal with suppressed exceptions.
Next TopicJava Type Inference for Generics |