4.4 Try-with-Resources & AutoCloseable
← Back to Chapter 4: Exception Handling
Introduced in Java 7, Try-with-Resources provides automated, deterministic deallocation for external resources (file handles, database connections, sockets), eliminating cumbersome finally cleanup boilerplate.
try-with-resources
This is an important modern Java feature.
Before try-with-resources:
Open resource
↓
Use resource
↓
finally
↓
Close resource
You had to manually close resources.
With try-with-resources:
try (SomeResource resource = ...) {
// use resource
}
Java automatically closes the resource after the try block.
The resource needs to implement:
AutoCloseable
or Closeable.
This is commonly used for:
Files
InputStream
OutputStream
Database resources
1. The Legacy Problem vs Try-with-Resources
Legacy Java 6 Cleanup (Clunky & Prone to Leakage):
FileInputStream fis = null;
try {
fis = new FileInputStream("report.pdf");
// read data...
} catch (IOException e) {
log.error("Read failed", e);
} finally {
if (fis != null) {
try {
fis.close(); // Can throw ANOTHER IOException!
} catch (IOException e) {
// Nested exception swallowing
}
}
}
Modern Try-with-Resources:
try (FileInputStream fis = new FileInputStream("report.pdf");
BufferedInputStream bis = new BufferedInputStream(fis)) {
// Automatically closed at the end of the try block!
byte[] data = bis.readAllBytes();
} catch (IOException e) {
log.error("File error: {}", e.getMessage());
}
Closing Order Rule
Multiple resources are closed in reverse order of their creation (the second resource is closed before the first resource).
Suppressed Exceptions
If an exception is thrown in the try block AND an exception occurs during .close(), the try block exception is prioritized and propagated. The secondary close exception is attached as a Suppressed Exception, inspectable via e.getSuppressed().