How does try-with-resources prevent JDBC connection and file-handle leaks?
Reviewed by Gurusankar M.
Short Answer
try-with-resources auto-closes any AutoCloseable in reverse order, even on exception, and suppresses-but-preserves close() errors. It replaces error-prone finally blocks that leak connections when close() itself throws or is forgotten.
On this page
Concept Made Simple
Coffee Chat Question
“How does try-with-resources prevent JDBC connection and file-handle leaks?”
Remember It Faster
Mind Map Answer
Resources declared in try (...) get close() called automatically — no manual finally, no leak if the body throws. Closes happen in reverse declaration order.
- Old finally
- verbose; leaks if close() throws
- try-with-resources
- auto close, exception-safe
- Suppressed
- close() error attached, not lost
Learn by Doing
Hands-on Keyboard
try (Connection c = ds.getConnection();
PreparedStatement ps = c.prepareStatement(SQL)) {
ps.setLong(1, id);
return ps.executeQuery();
} // c & ps closed automatically, even on exceptionThink Beyond the Expected
What If?
Your pool reports 'connection leak detected' under load — likely cause?
A code path acquires a Connection but an exception skips a manual close (or close() is in the wrong place). Switching to try-with-resources guarantees release on every path; pool 'leak detection' just surfaces the unreturned connection.
Real World
Connection-pool exhaustion (HikariCP timeouts) under peak load almost always traces to a non-try-with-resources path leaking connections during exceptions.
Interviewer's Expectation
Keywords they're listening for:
- AutoCloseable
- reverse-order close
- exception-safe
- suppressed exceptions
- pool exhaustion symptom
Common Mistakes
- Closing in catch instead of finally/try-with-resources
- Ignoring exceptions thrown by close()
- Reusing a resource after the try block
Best Practices
- Always acquire closeable resources in try-with-resources
- Keep one resource per declaration for clarity
- Set a pool leakDetectionThreshold in non-prod to catch leaks early
Follow-up Questions
- What is a suppressed exception and how do you read it?
- Why does HikariCP report leaks via leakDetectionThreshold?
- Order of close when multiple resources throw?
Continue Learning with AI
Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly — AI is your learning companion, not a shortcut.
Plain-language foundations
I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner. Topic: Exceptions (Core Java) Interview question: "How does try-with-resources prevent JDBC connection and file-handle leaks?" Please: 1. Explain the core idea in simple, plain language, using an everyday analogy. 2. Define any technical terms you use. 3. Walk through one small, concrete example. 4. Finish with a single sentence I can easily remember. Keep the tone friendly and assume I'm new to this topic.
Was this answer helpful?
Affiliate links
Tools for Your Developer Workspace
Equipment for a comfortable, productive setup.
As an Amazon Associate I earn from qualifying purchases.
- MonitorView on Amazon : BenQ EW2790U 27-inch Monitor (opens in a new tab)
BenQ EW2790U 27-inch Monitor
- LaptopView on Amazon : Acer Aspire One Laptop (opens in a new tab)
Acer Aspire One Laptop
- Office ChairView on Amazon : Wakefit Gravita Ergonomic Office Chair (opens in a new tab)
Wakefit Gravita Ergonomic Office Chair