Suppression Without Try-With-Resources
What You'll Learn
You'll learn how to manually replicate try-with-resources suppression behavior using the addSuppressed() method in traditional finally blocks.
The Manual Approach
While try-with-resources handles exception suppression automatically, you can achieve the same behavior manually. This is useful when working with resources that can't use try-with-resources or when maintaining legacy code.
The Throwable class provides the addSuppressed(Throwable exception) method specifically for this purpose. When you catch an exception and then encounter another exception (like during cleanup), you can attach the second exception as suppressed rather than losing it entirely.
How It Works
In a traditional try-finally block, if an exception occurs in the try block and another occurs in the finally block, the finally exception "wins" and the original is lost. To prevent this, you manually catch the finally exception and add it as suppressed to the original:
FileInputStream fis = null;
Throwable primaryException = null;
try {
fis = new FileInputStream("data.txt");
// risky operation that might throw
} catch (Exception e) {
primaryException = e;
throw e;
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception closeException) {
if (primaryException != null) {
primaryException.addSuppressed(closeException);
} else {
throw closeException;
}
}
}
}
This pattern preserves both exceptions—the primary one is thrown, and the close exception is attached as suppressed, accessible via getSuppressed().
Key Takeaway: While try-with-resources automates suppression, you can manually implement the same behavior using addSuppressed() in finally blocks to preserve all exception information when multiple failures occur.