Try with Resources

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:

try (ResourceType resource = expression) {
  // code that uses the resource
} catch (ExceptionType e) {
  // code to handle the exception
}

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:

try (FileInputStream inputStream = new FileInputStream("file.txt")) {
    // code that uses the input stream
} catch (IOException e) {
    // code to handle the exception
}

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:

try (ResourceType1 resource1 = expression1; ResourceType2 resource2 = expression2) {
  // code that uses the resources
} catch (ExceptionType e) {
  // code to handle the exception
}

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:

try (FileInputStream inputStream = new FileInputStream("file.txt");
     FileOutputStream outputStream = new FileOutputStream("file-copy.txt")) {
    // code that uses the input and output streams
} catch (IOException e) {
    // code to handle the exception
}

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.

Leave a Reply

Your email address will not be published. Required fields are marked *