Middle
How does the try-with-resources operator work in Java?
sobes.tech AI
Answer from AI
The try-with-resources operator ensures automatic closing of resources that implement the java.lang.AutoCloseable interface.
Mechanism:
- In parentheses after the
trykeyword, one or more resources are declared and/or initialized, separated by semicolons. - These resources must implement the
AutoCloseableinterface, which has a single methodclose():public interface AutoCloseable { void close() throws Exception; } - After the
tryblock completes (whether successfully or due to an exception), the Java machine automatically calls theclose()method on each resource declared in parentheses, in the reverse order of their declaration. - If exceptions are thrown in the
tryblock or when closing resources:- If an exception is thrown both in the
tryblock and when closing a resource, the exception from thetryblock is primary, and the exception during closing is suppressed and can be retrieved using thegetSuppressed()method on the main exception. - If an exception is thrown only during resource closing, it propagates further.
- If an exception is thrown both in the
Advantages:
- Simplifies code and prevents resource leaks.
- Eliminates the need for explicit
close()calls in afinallyblock. - Properly handles cases where exceptions are thrown both in the main block and during resource closing.
Example:
Traditional approach with finally:
// Explicit resource closing in finally
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 e) {
e.printStackTrace();
}
}
}
Using try-with-resources:
// Automatic resource closing
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
String line = reader.readLine();
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
Multiple resources:
// Multiple resources, closed in reverse order of declaration
try (
FileInputStream fis = new FileInputStream("in.txt");
FileOutputStream fos = new FileOutputStream("out.txt")
) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}