I have an application which uses two methods of an API. Both these methods throw more than five exceptions each. So, if I just add a throws declaration then it becomes a list of more than ten. (My method cannot handle any of the ten exceptions)
I have read that throwing a long list of exceptions is a bad practice. Also throwing (the umbrella) Exception is a bad practice. So, what should I do?
Edit: Added choice 5.
"2. Create a custom exception class", but not for all. Wrap the exceptions in logical groups. For example you can have XmlWritingException
, PaymentGatewayException
and DataAccessException
which wrap different exceptions depending on the scenario.
It's even possible (and preferred) to wrap the same exception in different wrapper. For example you can wrap IOException
in PaymentGatewayException
if payment has failed due to communication problem, but in XmlWritingException
if it has failed during some i/o operation with xml. All these examples are hypothetical, but you get the idea.
Most importantly - set the original exception as a cause of the new one, so that it does not get lost.
Update: In fact option 5 is fine in case you can't expect the client to reasonably recover from the exception. Even better - the custom exceptions you create can extend RuntimeException
. That's what spring does, for example, wrapping all data-related exceptions in DataAccessException
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With