try-with-resources / AutoCloseable
A syntax for automatically closing resources such as files and network connections. Declare the resource inside the parentheses of try, and close() is called automatically when the block exits (Java 7+).
Syntax
// Automatically closes the resource when the block exits (Java 7+).
try (ResourceType res = new ResourceType()) {
// Code using res
} catch (Exception e) {
// Exception handling
}
// Multiple resources can be declared, separated by semicolons.
try (
ResourceType1 res1 = new ResourceType1();
ResourceType2 res2 = new ResourceType2()
) {
// Code using res1 and res2
}
// Define a custom class that implements AutoCloseable.
class MyResource implements AutoCloseable {
@Override
public void close() {
System.out.println("Resource closed.");
}
}
Main Interfaces and Classes
| Interface / Class | Description |
|---|---|
| AutoCloseable | An interface that declares the close() method. Resources used with try-with-resources must implement this. |
| Closeable | An interface in the java.io package. It extends AutoCloseable and declares that it throws IOException. |
| BufferedReader | A file-reading class that implements Closeable. |
| FileInputStream | A byte stream class that implements Closeable. |
| Connection (java.sql) | A database connection class that implements AutoCloseable. |
Sample Code
import java.io.*;
// Safely read a file using try-with-resources.
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Failed to read file: " + e.getMessage());
}
// br.close() is called automatically when the block exits.
// Handle multiple resources at the same time.
try (
FileInputStream fis = new FileInputStream("input.txt");
FileOutputStream fos = new FileOutputStream("output.txt")
) {
int b;
while ((b = fis.read()) != -1) {
fos.write(b);
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
// Implement AutoCloseable in a custom class.
class Connection implements AutoCloseable {
public Connection() { System.out.println("Connected."); }
@Override
public void close() { System.out.println("Disconnected."); }
}
try (Connection conn = new Connection()) {
System.out.println("Processing data...");
}
// Output:
// "Connected."
// "Processing data..."
// "Disconnected."
Notes
Before try-with-resources, you had to call close() explicitly in a finally block. This syntax prevents you from forgetting to close resources and keeps your code concise. When multiple resources are declared, they are closed in reverse order of declaration.
To use try-with-resources, the resource class must implement AutoCloseable (or Closeable). If an exception is thrown inside close(), it is recorded as a "suppressed exception" alongside any exception from the try block. You can retrieve it with e.getSuppressed().
For the basic syntax of exception handling, see 'try / catch / finally / throw'.
If you find any errors or copyright issues, please contact us.