DEV Community

Code Green for CodeGreen

Posted on

What is Try-With-Resources, in Java? #InterviewQuestion

What is Try-With-Resources?

Try-with-resources in Java is a feature introduced in Java 7 to automatically manage resources that implement AutoCloseable or Closeable interfaces. It ensures these resources are closed properly after they are no longer needed, even if an exception occurs.

Example

public class TryWithResourcesExample {
    public static void main(String[] args) {
        String fileName = "example.txt";

        try (FileReader fileReader = new FileReader(fileName);
             BufferedReader bufferedReader = new BufferedReader(fileReader)) {

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }

        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Explanation

  • Syntax: Resources are declared within the parentheses of the try statement.
  • Automatic Closing: After the try block finishes execution, or if an exception occurs, the resources are automatically closed in the reverse order of their creation.
  • Exception Handling: Any exceptions that occur within the try block can be caught and handled in the catch block as usual.

Conclusion

Try-with-resources simplifies resource management in Java programs by ensuring that resources are closed properly without needing explicit finally blocks. It improves code readability and reduces the likelihood of resource leaks.

Top comments (0)