What is try-with-resources for?
Options
- Trying several resources in parallel until one works
- Closing resources automatically, even after an error (Correct option)
- Retrying an operation again and again until it succeeds
- Allocating extra memory to the resource when needed
Answer
Automatically closing resources (files, connections) at the end of the block, even if an exception happens
Why
Resources such as files, database connections and sockets must be closed or they leak. The old way needed a finally block with extra try/catch.
With try (Resource r = ...) { ... }, Java calls r.close() automatically when the block ends, normally or by exception. The resource must implement AutoCloseable. Resources close in reverse order of creation.
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
System.out.println(br.readLine());
} // br.close() is called automaticallyRemember
Open it in the try parentheses and Java closes it for you.