Member-only story
Caution when using Try-With-Resources in Java
The try-with-resources statement in Java is a powerful feature introduced in Java 7 to simplify resource management. It ensures that resources like streams, files, and connections are closed automatically, reducing the likelihood of resource leaks. However, there are important considerations and potential pitfalls when using this construct.
Not a Medium member? No problem! Read the full article here. Enjoy!
How to handle Try-With-Resources with caution
1. Ignoring Suppressed Exceptions
When multiple resources are used in a try-with-resources block, if both the try block and the close method of a resource throw exceptions, the exception from the close method is suppressed. Failing to handle suppressed exceptions can lead to critical debugging oversights.
Bad Practice:
try (
ResourceA resA = new ResourceA();
ResourceB resB = new ResourceB()
) {
throw new RuntimeException("Primary Exception in try block");
} // The exception from close() on resB is suppressed and ignoredExplanation:
- If
resB.close()It also throws an exception; it will be suppressed by the runtime and not printed unless explicitly handled.










