Try-with-resources statement is a feature introduced in Java 7 that allows you to automatically close resources that are used within a try block. This feature is particularly useful when working with resources such as file streams, sockets, and database connections, which need to be closed after they are no longer needed.
The basic syntax for the try-with-resources statement is as follows:
For example, the following code snippet shows how you can use the try-with-resources statement to automatically close a FileInputStream after it is no longer needed:
In the above example, the FileInputStream is automatically closed when the try block is exited, regardless of whether an exception is thrown or not. This eliminates the need to manually close the resource in a finally block.
It is important to note that the try-with-resources statement only works with objects that implement the AutoCloseable interface and its subinterface, Closeable. Also, any exception thrown by the try block or the close() method will be suppressed, and the primary exception will be the one that is thrown by the try block.
try with multiple resources
it is possible to use the try-with-resources statement with multiple resources by specifying them comma-separated within the parentheses. The resources will be closed in the reverse order they were opened.
The basic syntax for try-with-resources statement with multiple resources is as follows:
For example, the following code snippet shows how you can use the try-with-resources statement to automatically close two resources, a FileInputStream and a FileOutputStream, after they are no longer needed:
In the above example, both the FileInputStream and the FileOutputStream are automatically closed when the try block is exited, regardless of whether an exception is thrown or not, and in reverse order of opening them.