views:

53

answers:

2

My question is: how would you create exception hierarchy in your application?

Designing the architecture of an application, from my perspective, we could have three types of exceptions:

  • the built-in (e.g.: InvalidOperationException)
  • custom internal system faults (DB transaction failed on commit, DbTransactionFailedException)
  • custom business exceptions (BusinessRuleViolationException)

Class hierarchy:

  • Exception
    • MyAppInternalException
      • DbTransactionFailedException
      • MyServerTimeoutException
      • ...
    • MyAppBusinessRuleViolationException
      • UsernameAlreadyExistsException
      • ...

where only MyAppInternalException & MyAppBusinessRuleViolationException would be catched.

+3  A: 

The real benefit of exception type E inheriting from type F is apparently when E is caught by a module that doesn't specifically know what E is, but does know about F. Assuming the inheritance makes sense, the module has a reasonable hope of taking the right corrective action for an E exception, based on it being a kind of E exception.

So I tend to class exceptions according to how they can reasonably be handled. For example, a typical business process might use something like:

  • ConfigurationException -- things that can be fixed by changing a config file. E.g. config cannot be parsed or is not consistent. Appropriate response is to warn the user to fix the config (with helpful hints if possible).
  • InfrastructureException -- things that can sporadically go wrong with resources outside the program's control, like remote servers, etc. Appropriate response is often to disconnect and retry after a pause, and give up if there are too many failures.
  • DataException -- things that are wrong in incoming data. An appropriate response is to log the complaint (and possibly the data) and ignore this message.

These can be subclassed of course. But distinction at that level is often more useful to modules closer to the source of the exception. If an exception bubbles all the way to main module then there are usually only a few possible actions, and it easiest to have a one-to-one correspondence between those actions and the catch statements they respond to.

Edmund
A: 

"UsernameAlreadyExistsException"

I think you shouldn't use an exception to control regular flow of your application. i.e. This is a regular business case and shouldn't appear as an exception. There is no MyAppBusinessRuleViolationException in a correct application design.

Regards,

Alexis