Ok, this is a doubt I always have when I’m writing any API, a.k.a., code reusable.
What do you do with exceptions? There are different possibilities:
-
Always throw them to the client. The exceptions are acumulative, so if method A uses the private method B and method B throws an exception and method A throws another exception, the client sees 2 exceptions and only should see the latest because is the method that he is invoking. We can acumulate a lot of exceptions.
-
Only throw the exceptions produced on the method that the client invokes. What do we do with the internal exceptions? Just print the exception (
printStackTrace())? Convert this checked exceptions to unckecked exceptions so we only have to throw them? -
Implement an interface that the client can use to set his prefered Log. I simply refuse do this.
-
Extend a
RuntimeExceptionand always throw your customized unchecked exception. All the methods published to the client are well explained and says that the methods can throw the exception if the contract is fulfilled. I like this technique.
Regarding your first point – it’s always better to create a domain-specific hierarchy of exceptions for your API (e.g. spring’s DataAccessExceptions) and wrap everything that goes out to your clients.
The rule of thumb regarding checked/unchecked exceptions is:
Regarding the second point – never hide internal errors if they affect the client in any way. Also, don’t output the error information into a side channel (like
e.printStackTrace()) the client might not be aware of. If you need to provide non-exceptional information to your users, you have two options:Loggerof some kindslf4j-api