Java Programming: Effective Use of Try-With-Resources Explained (Part-3 of JAVA SE Exceptions Series)

TL;DR:
Learn how to use Java's try-with-resources statement for efficient resource management, ensuring automatic closure of resources like file streams and database connections to prevent leaks.
The try-with-resources statement ensures that resources are closed after the program is finished with them. This feature was introduced in Java 7.
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("I/O error: " + e.getMessage());
}
Resources such as file streams, database connections, or network sockets need to be closed after their operations are complete to prevent resource leaks. This ensures that the BufferedReader is closed automatically, even if an exception occurs.
How try-with-resources Works
The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The object used in a try-with-resources statement must implement the java.lang.AutoCloseable interface, which includes the close() method.
try (ResourceType resource = new ResourceType()) {
// Use the resource
} catch (ExceptionType e) {
// Handle the exception
}
When the try block finishes, the close() method of each resource is called automatically.
Before Java 7, handling resources like file streams required explicit closing in afinallyblock
Traditional Resource Management usingtry-catch-finally:
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("I/O error: " + e.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.out.println("Error closing reader: " + e.getMessage());
}
}
}
Usingtry-with-resources:
Using try-with-resources, the same functionality can be achieved more concisely:
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("I/O error: " + e.getMessage());
}
Multiple Resources
try-with-resources can manage multiple resources, each declared within the parentheses and separated by semicolons.
try (
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))
) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
System.out.println("I/O error: " + e.getMessage());
}
In this example, both BufferedReader and BufferedWriter are closed automatically when the try block exits, even if an exception occurs.
Custom AutoCloseable Resources
To use a custom resource with try-with-resources, the resource must implement the AutoCloseable interface.
public class CustomResource implements AutoCloseable {
public void doSomething() {
System.out.println("Doing something with the resource");
}
@Override
public void close() throws Exception {
System.out.println("Closing the resource");
}
}
public class CustomResourceExample {
public static void main(String[] args) {
try (CustomResource resource = new CustomResource()) {
resource.doSomething();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
In this example, CustomResource implements AutoCloseable, and its close() method is called automatically when the try block finishes.
Related official doc links:
https://docs.oracle.com/javase/8/docs/api/java/lang/Exception.html
Related official explainer links:
https://docs.oracle.com/javase/specs/jls/se13/html/jls-11.html
https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html



