Course contentsShow
← Java
Lesson 849 of 2,87020. Try-With-Resources and Resource ManagementFree lesson

Manual close() Calls Are Error-Prone

Examining how forgetting to call close() or placing it incorrectly leads to resource leaks in production code.

Manual close() Calls Are Error-Prone

What you'll learn: You'll discover why manually calling close() in traditional try-finally blocks frequently leads to bugs and resource leaks in real-world code.

The Human Factor in Resource Management

Even experienced developers make mistakes when manually managing resources. While the traditional try-finally pattern seems straightforward, it's surprisingly easy to get wrong. Let's examine the common pitfalls.

Common Mistakes

Forgetting close() entirely: In the rush of development, programmers sometimes open a resource and simply forget to close it. Without compiler enforcement, this silent error only surfaces when your application runs out of file handles or database connections.

Placing close() in the wrong block: Beginners often write close() inside the try block instead of finally. If an exception occurs before reaching that line, the resource never closes.

Ignoring exceptions during close(): When you call close() manually in finally, you must wrap it in its own try-catch because close() can throw exceptions. Many developers skip this, causing the exception from close() to mask the original exception.

Forgetting null checks: If resource initialization fails, your variable might be null. Calling close() on null in finally throws NullPointerException, hiding the actual problem.

The Real-World Impact

These mistakes compound in production code. A missed close() call might not immediately crash your application—instead, it slowly leaks resources until your system exhausts available handles hours or days later. Debugging becomes a nightmare because the symptom (resource exhaustion) appears far from the cause (the forgotten close()).

Multiple resources make this exponentially worse. Closing three resources properly requires nested try-finally blocks and careful null checking—tedious, error-prone, and ugly code.

Key Takeaway: Manual close() calls rely on perfect developer discipline and are inherently fragile; forgetting, misplacing, or incorrectly handling close() leads to resource leaks that are difficult to detect and debug in production environments.