Best Practices for Suppressed Exceptions
What you'll learn: How to design your resource cleanup code to minimize suppressed exceptions and ensure critical errors aren't lost in logs.
Understanding the Problem
When exceptions occur during resource cleanup in try-with-resources blocks, they can be suppressed by exceptions from the main try block. While this mechanism prevents losing the primary error, it means cleanup failures might go unnoticed if you don't actively check for them.
Think of it like a fire alarm going off during a building evacuation: the evacuation (primary exception) is the main concern, but you still need to know the alarm malfunctioned (suppressed exception) so you can fix it later.
Core Best Practices
Log suppressed exceptions explicitly. Don't rely on default exception output. In production code, actively retrieve and log suppressed exceptions:
try (Resource resource = new Resource()) {
// work with resource
} catch (IOException e) {
logger.error("Primary error: " + e.getMessage());
for (Throwable suppressed : e.getSuppressed()) {
logger.warn("Suppressed during cleanup: " + suppressed.getMessage());
}
}
Make close() methods robust. When implementing AutoCloseable, ensure your close() method never throws unless absolutely necessary. Catch and log internal errors when possible rather than propagating them.
Never throw from close() if already closed. Implement idempotent close methods that safely handle multiple calls without throwing exceptions.
Monitor suppressed exceptions in production. Set up alerts or metrics tracking when suppressed exceptions occur—they often indicate resource leaks or configuration problems that need attention.
Document close() behavior clearly. If your close() method can throw specific exceptions, document when and why, so callers can decide whether to check suppressed exceptions.
Key Takeaway: Suppressed exceptions are not "handled" exceptions—actively log and monitor them to catch resource management issues before they become critical production problems.