Should a control library that runs user-supplied code intercept Exceptions or Throwables?

StackOverflow https://stackoverflow.com/questions/15303035

  •  18-03-2022
  •  | 
  •  

Frage

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 Exceptions like above, or should I also intercept Throwables? If an Error occurs, is there any chance that

  • JVM will recover? (So is there any point running finalizers?)
  • JVM will be in such a state that it's actually possible to run them?

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 Exceptions, or also Throwables? Ignoring and not rethrowing Errors seem more problematic.

War es hilfreich?

Lösung

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.

Andere Tipps

I believe that if you're dealing with user supplied code that you can assume nothing about, then you should catch throwable (in both cases), consider linkage errors that don't affect the whole system, just the executing code like: NoSuchMethodError or NoClassDefFoundError

If you want to give up in case of an error effecting the whole system then you can not catch or rethrow Errors that extends VirtualMachineError like OOME.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top