Middle
What is try-with-resources used for?
sobes.tech AI
Answer from AI
try-with-resources is used for automatic closing of resources that implement the AutoCloseable interface (such as streams, database connections, files). This helps prevent resource leaks and simplifies code, as there is no need to explicitly call the close() method in a finally block.
Example:
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line = br.readLine();
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
// BufferedReader will automatically close after exiting the try block
Thus, try-with-resources guarantees proper resource release even when exceptions occur.