Exceptionseasy0-2 years

A method opens a database connection in a `try-with-resources` block. The body throws a business exception, and `close()` on the connection also throws (the pool rejects a broken connection). What does the caller actually catch, and where did the `close()` failure go?

The caller catches the original business exception from the body — that's the one that propagates. The close() failure isn't lost, but it also isn't the exception the caller sees directly: it's attached to the body's exception as a suppressed exception, retrievable through getSuppressed() and printed in the stack trace under Suppressed:. This is exactly the problem the old manual finally { conn.close(); } pattern couldn't solve — there, if close() threw, it replaced the body's exception outright, and whoever was debugging saw "connection close failed" with no idea the real problem was a business rule violation three lines earlier. try-with-resources keeps the primary failure as primary and preserves the secondary one alongside it instead of discarding either.

The lesson behind it →
More on Exceptions