I've seen here many general questions about the difference between Exception
and Throwable
. I know the difference, and I have a more specific question.
I'm writing a library that binds and runs together several user-supplied pieces of code. If one of the pieces fails, the whole computation is discarded. In order to keep resource usage clean, users can also supply finalizers that are run when such an event happens. The patterns is something like this:
try {
// process ...
} catch (Exception ex) {
runRegisteredFinalizers();
throw ex;
}
My question is: Should I intercept and rethrow just Exception
s like above, or should I also intercept Throwable
s? If an Error
occurs, is there any chance that
Also, when running finalizers, I catch and ignore their exceptions so that other registered finalizers have a chance to run, something like:
try {
finalizer.run();
}
catch (Exception ex) {
log.error("Exception in a finalizer", ex);
}
Again, should I intercept just Exception
s, or also Throwable
s? Ignoring and not rethrowing Error
s seem more problematic.
Maybe the safest thing to do would be to catch Throwable (or Exception and Error separately) and pass in the reference of what was caught to your runRegisteredFinalizers() giving the user a chance to decide if it is something they should care about.
However, errors that you would be catching would be either specific to your toolkit (not necessarily from the users code), or things that the user did not account for (assuming they would have trapped the case themselves). In these cases, the type of exception doesnt matter.
In either case though, depending on the nature of your toolkit and the potential impact on missing a Error, it might make sense to catch that as well.