Introduction
Managing system resources such as files, database connections, network sockets, and input/output streams is an essential part of Java programming. These resources consume memory and operating system resources, so they must be released properly after use. If resources are not closed correctly, applications can suffer from memory leaks, file locks, reduced performance, and unexpected errors.
Before Java 7, developers typically used a try-catch-finally block to ensure resources were closed manually. While effective, this approach often resulted in lengthy and repetitive code. It also increased the risk of forgetting to close a resource or handling exceptions incorrectly.
To simplify resource management, Java 7 introduced the Try-with-Resources statement. This feature automatically closes resources that implement the AutoCloseable interface, even if an exception occurs. It makes code shorter, cleaner, safer, and easier to maintain.
What is Java Try-with-Resources?
Try-with-Resources is a special form of the try statement introduced in Java 7 that automatically closes resources after they are no longer needed.
Instead of manually closing resources in a finally block, you declare the resources inside the parentheses of the try statement.
When execution leaves the try block, Java automatically closes every declared resource in the reverse order of their creation.
This feature greatly simplifies resource management and reduces the risk of resource leaks.
Why Use Try-with-Resources?
Using Try-with-Resources offers several advantages:
- Automatically closes resources
- Reduces boilerplate code
- Prevents resource leaks
- Improves code readability
- Simplifies exception handling
- Eliminates most cleanup code
- Recommended by modern Java best practices
It is especially useful when working with:
- Files
- Input streams
- Output streams
- Readers
- Writers
- Database connections
- Network sockets
Syntax of Try-with-Resources
try (ResourceType resource =
new ResourceType()) {
// Use the resource
} catch (Exception e) {
// Handle exception
}
The resource declared inside the parentheses is automatically closed after the try block finishes.
How Try-with-Resources Works?
The execution flow is:
- Java creates the resource.
- The code inside the try block executes.
- If an exception occurs, it is handled by the appropriate catch block.
- Java automatically closes all declared resources.
- Program execution continues.
The developer does not need to explicitly call the close() method.
The AutoCloseable Interface
A resource can be used with Try-with-Resources only if it implements the AutoCloseable interface.
The AutoCloseable interface defines a single method:
void close() throws Exception;
Many standard Java classes implement this interface, including:
- FileInputStream
- FileOutputStream
- BufferedReader
- BufferedWriter
- Scanner
- PrintWriter
- Connection
- Statement
- ResultSet
- ZipFile
When the try block completes, Java automatically calls the close() method.
Example: Reading a File
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (BufferedReader reader =
new BufferedReader(
new FileReader("data.txt"))) {
System.out.println(
reader.readLine()
);
} catch (IOException e) {
System.out.println(
e.getMessage()
);
}
}
}
The BufferedReader is automatically closed after the try block.
Example: Writing to a File
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (BufferedWriter writer =
new BufferedWriter(
new FileWriter("output.txt"))) {
writer.write(
"Welcome to Java!"
);
} catch (IOException e) {
e.printStackTrace();
}
}
}
No manual close() call is required.
Using Multiple Resources
Multiple resources can be declared in the same try statement.
import java.io.*;
public class Main {
public static void main(String[] args) {
try (
FileReader fr =
new FileReader("input.txt");
BufferedReader br =
new BufferedReader(fr)
) {
System.out.println(
br.readLine()
);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Resources are automatically closed in the reverse order of their declaration.
Try-with-Resources and Exceptions
If an exception occurs while using a resource, Java still closes the resource automatically.
import java.io.*;
public class Main {
public static void main(String[] args) {
try (
BufferedReader reader =
new BufferedReader(
new FileReader("data.txt"))
) {
int result = 10 / 0;
} catch (Exception e) {
System.out.println(
e.getMessage()
);
}
}
}
Even though an ArithmeticException occurs, the BufferedReader is closed automatically.
Try-with-Resources vs finally
| Try-with-Resources | finally Block |
|---|---|
| Introduced in Java 7 | Available since early Java versions |
| Automatically closes resources | Resources must be closed manually |
| Less code | More boilerplate code |
| Lower risk of resource leaks | Easier to forget close() |
| Recommended for AutoCloseable resources | Useful for general cleanup tasks |
Creating Your Own AutoCloseable Class
You can create custom resources by implementing the AutoCloseable interface.
class MyResource
implements AutoCloseable {
public void display() {
System.out.println(
"Using resource."
);
}
@Override
public void close() {
System.out.println(
"Resource closed."
);
}
}
Using the custom resource:
public class Main {
public static void main(String[] args) {
try (MyResource resource =
new MyResource()) {
resource.display();
}
}
}
Output
Resource closed.
Real-Life Example
Suppose an application reads employee records from a file.
import java.io.*;
public class EmployeeApp {
public static void main(String[] args) {
try (
BufferedReader reader =
new BufferedReader(
new FileReader(
"employees.txt"))
) {
String line;
while ((line =
reader.readLine())
!= null) {
System.out.println(line);
}
} catch(IOException e) {
System.out.println(
"Unable to read file."
);
}
}
}
Regardless of whether an exception occurs, the file is closed automatically.
Advantages of Try-with-Resources
- Automatic resource management
- Cleaner code
- Improved readability
- Fewer programming errors
- Prevents resource leaks
- Simplifies maintenance
- Better exception handling
- Recommended by modern Java standards
Common Mistakes
1. Using Resources That Do Not Implement AutoCloseable
Only classes implementing AutoCloseable or Closeable can be used directly in a Try-with-Resources statement.
2. Closing Resources Manually
Incorrect:
resource.close();
Inside a Try-with-Resources block, manual closing is unnecessary and may even cause issues if attempted prematurely.
3. Ignoring Exceptions
Always catch or declare exceptions appropriately. Automatic resource management does not replace proper exception handling.
4. Using Try-with-Resources for Non-Resource Objects
Regular objects that do not require cleanup do not belong in the resource declaration.
5. Forgetting Resource Scope
Resources declared inside the try statement are only accessible within the try block.
Best Practices
- Prefer Try-with-Resources for all AutoCloseable resources.
- Keep the resource declaration simple and readable.
- Use meaningful variable names.
- Catch specific exceptions where possible.
- Avoid manually closing automatically managed resources.
- Keep business logic separate from resource management.
- Use multiple resources in one try statement only when they are related.
Conclusion
Java Try-with-Resources is one of the most valuable enhancements introduced in Java 7. It simplifies resource management by automatically closing files, streams, database connections, sockets, and other objects that implement the AutoCloseable interface. This reduces boilerplate code, minimizes the risk of resource leaks, and makes applications easier to read and maintain.
Compared with the traditional try-catch-finally approach, Try-with-Resources offers a cleaner and more reliable way to manage resources. By understanding how it works, using it with AutoCloseable objects, and following best practices, you can write safer, more efficient, and production-ready Java applications. Mastering this feature is also essential for Java interviews and modern enterprise software development.