javaexceptionclient-library

Catch and wrap runtime exceptions when creating library?


I am writing a client library for a range of our APIs to be used by third party libraries.

There underlying http client we are using only throws RuntimeExceptions. I don't want to let these exceptions bubble up, but instead wrap them in our own ClientException.

However everything I read seems to suggest that catching runtime exceptions is really bad practice?

Is this an exception to the rule when writing libraries to be used by third parties?


Solution

  • There is nothing wrong with catching an unchecked exception, especially with the purpose of wrapping and rethrowing.

    The only case to which an advice not to catch unchecked exceptions may apply is writing something like

    try { ... }
    catch (RuntimeException e) { ... do some handling and move on ... }
    

    because that will stop any NullPointerExceptions, IllegalArgumentExceptions, etc. from breaking the execution flow. These exceptions are both too generic to be automatically recovered from (could appear at too many places, for too many different reasons), and usually indicate programming errors which will be more difficult to pinpoint if the code doesn't break on them.