How try-with-resources handles dependent resources in Java

How try-with-resources Handles Dependent Resources in Java Last week, I talked about how try-with-resources made it easier to close connections automatically. But what about when one resource depends on another — like a ResultSet that relies on a PreparedStatement, which relies on a Connection? Before (old way): Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement("SELECT * FROM orders WHERE customer_id = ?"); stmt.setInt(1, id); rs = stmt.executeQuery(); while (rs.next()) { process(rs); } } finally { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } After (try-with-resources): try (Connection conn = dataSource.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM orders WHERE customer_id = ?"); ResultSet rs = stmt.executeQuery()) { while (rs.next()) { process(rs); } } Java automatically closes everything in reverse order of creation: ResultSet → Statement → Connection No leaks, no nested finally blocks, no forgotten close calls. It’s small things like this that make Java cleaner every release. 👉 Did you know try-with-resources handled dependencies this neatly? #Java #CleanCode #SoftwareEngineering #Refactoring #Java17 #BestPractices

To view or add a comment, sign in

Explore content categories