Java Try-With-Resources
When working with files, input/output streams, database connections, or other external resources, it is important to close them after use. If resources remain open, they may continue consuming system memory or lock files, preventing other processes from accessing them.
In earlier versions of Java, developers had to manually close resources using the close() method. However, forgetting to close a resource could lead to memory leaks, file access issues, and unstable applications.
To solve this problem, Java 7 introduced the try-with-resources statement, which automatically closes resources when they are no longer needed.
Note: File handling and streams will be explained in detail in later chapters. For now, focus on how try-with-resources manages resource cleanup automatically.
Closing Resources Manually (Traditional Approach)
Before Java 7, resources needed to be closed manually inside the try block or a finally block.
This approach worked, but it required extra code and increased the chance of mistakes.
Example: Manual Resource Closing
import java.io.FileWriter;
import java.io.IOException;
public class FileWriteManualClose {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("message.txt");
writer.write("Welcome to Java programming!");
writer.close(); // Manual resource closing
System.out.println("File written successfully.");
}
catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
}
}
}
Explanation
- The program creates a FileWriter object to write text to a file.
- After writing the data, the program explicitly calls close().
- If the developer forgets to close the resource, the file may remain open until the program
- finishes.
- This manual process can become complex when working with multiple resources.
Java Try-With-Resources
The try-with-resources statement simplifies resource management by automatically closing resources once the try block finishes execution.
Resources are declared inside parentheses immediately after the try keyword. When the block completes—whether normally or due to an exception—Java automatically calls the close() method.
Syntax
try (ResourceType resource = new ResourceType()) {
// Code that uses the resource
}
catch (ExceptionType e) {
// Exception handling
}
The resource must implement the AutoCloseable interface, which ensures that the close() method can be called automatically.
Example: Using Try-With-Resources
import java.io.FileWriter;
import java.io.IOException;
public class TryWithResourcesExample {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("output.txt")) {
writer.write("Learning Java exception handling.");
System.out.println("Data written to file successfully.");
}
catch (IOException e) {
System.out.println("File operation failed.");
}
}
}
What Happens Here?
- The FileWriter resource is created inside the try() statement.
- The program writes data to the file.
- When execution leaves the try block, Java automatically closes the file resource.
- Even if an exception occurs, the resource is still properly closed.
- This makes the code safer and easier to maintain.
Using Multiple Resources
Java also allows multiple resources inside a single try-with-resources statement. Each resource is separated by a semicolon.
Example
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class MultipleResourcesExample {
public static void main(String[] args) {
try (
FileWriter fileWriter = new FileWriter("data.txt");
BufferedWriter buffer = new BufferedWriter(fileWriter)
) {
buffer.write("Java try-with-resources simplifies resource management.");
buffer.newLine();
buffer.write("Resources are closed automatically.");
System.out.println("Data written successfully.");
}
catch (IOException e) {
System.out.println("Error writing to file.");
}
}
}
In this example:
Both FileWriter and BufferedWriter are automatically closed when the try block finishes.
Advantages of Try-With-Resources
Using try-with-resources offers several important benefits:
1. Automatic Resource Closure
Resources are always closed automatically, even when exceptions occur.
2. Cleaner Code
Developers no longer need to manually call close() or write additional cleanup logic.
3. Reduced Boilerplate Code
The syntax eliminates unnecessary finally blocks used solely for closing resources.
4. Improved Reliability
Ensures that system resources such as files, sockets, and streams are released properly