Sitemap
Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Caution when using Try-With-Resources in Java

4 min readDec 3, 2024

--

Press enter or click to view image in full size

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 ignored

Explanation:

  • If resB.close() It also throws an exception; it will be suppressed by the runtime and not printed unless explicitly handled.

--

--

Nithidol Vacharotayan
Nithidol Vacharotayan

Written by Nithidol Vacharotayan

I write about production failures in Java backend systems: Spring Boot, Kafka, Redis, PostgreSQL, and the trade-offs that only show up after launch.

Dev Genius
Dev Genius

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development