Senior
Как работали с ресурсами до появления try-with-resources?
sobes.tech AI
Answer from AI
Before the introduction of the try-with-resources statement in Java (prior to Java 7), resource management (such as streams, files, connections) was handled manually using a try-finally block.
The resource was opened before the try block, and in the finally block, it was closed to prevent resource leaks even if exceptions occurred.
Example:
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("file.txt"));
String line = reader.readLine();
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
This approach was more verbose and prone to errors if the resource was not closed or if exceptions during closing were not handled properly.