Junior — Middle
What is the difference between try-catch and try-with-resources constructs in exception handling and resource management?
sobes.tech AI
Answer from AI
The try-catch construct is used for exception handling: code that may throw an exception is placed in the try block, and exception handling code is placed in the catch block.
try-with-resources (introduced in Java 7) is a special form of try that automatically manages resources implementing the AutoCloseable interface (e.g., streams, files, database connections). Resources are declared in parentheses after try, and they are automatically closed after the block, even if an exception occurs.
Example:
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line = br.readLine();
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
Here, BufferedReader will be automatically closed after the block, eliminating the need to write a finally block with close().
Summary:
try-catch— for exception handling.try-with-resources— for automatic resource closing and exception handling.