Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw a long list of exceptions vs throw an Exception vs throw custom exception?

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?

  1. Add a try catch block, and log and exit in the catch block?
  2. Create a custom exception class, wrap every exception and throw the custom exception?
  3. Add a throws declaration for all exceptions?
  4. Throw Exception?
  5. Add a try catch block, and throw a RuntimeException in the catch block? (Current approach)

Edit: Added choice 5.

like image 592
athena Avatar asked Dec 23 '10 15:12

athena


1 Answers

"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.

like image 79
Bozho Avatar answered Dec 07 '22 10:12

Bozho