Junior — Middle
Explain the mechanism of using try-catch with resources in programming languages.
sobes.tech AI
Answer from AI
In Java, for working with resources that require closing (such as files, streams, database connections), the try-catch-finally construct is often used. However, starting with Java 7, try-with-resources was introduced, which automatically closes resources.
The try-with-resources mechanism allows:
- Handling exceptions that occur when working with resources.
- Guaranteeing the closing of resources even if exceptions occur.
Example with try-with-resources:
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
String line = reader.readLine();
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
In this example, BufferedReader will automatically close after the try block executes, even if an exception occurs.