Firstly, sorry for asking a question on what must be a well-worn topic. I've come across loads of questions with answers suggesting to swallow (catch and ignore/log) potential exception from methods that close resources in finally blocks. It seems to be a generally accepted pattern. But I haven't yet seen anybody explain why. Here's just one example: Try-catch-finally and then again a try catch.
I understand that any exception thrown from a finally block will "mask" any exception thrown in the corresponding try block, but I don't see why this is a bad thing. For example:
Resource r = new Resource();
try {
r.use();
other();
} finally {
r.close();
}
My current understanding is:
- If only
close
throws an exception, we definitely don't want to swallow it. - If both
use
andclose
throw an exception, it's probably for the same underlying reason, and it doesn't matter which exception gets propagated up (they both would contain equally useful information?). - If both
other
andclose
throw an exception, there are two unrelated problems. Arguably the one that happened first should propagate, but there isn't any reason to suggest that the first exception caused the second (is there?), so either will do.
What am I wrong about?