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 (database transaction failed on commit, DbTransactionFailedException)
- custom business exceptions (BusinessRuleViolationException)
Class hierarchy:
- Exception
- MyAppInternalException
- DbTransactionFailedException
- MyServerTimeoutException
- …
- MyAppBusinessRuleViolationException
- UsernameAlreadyExistsException
- …
- MyAppInternalException
where only MyAppInternalException & MyAppBusinessRuleViolationException would be catched.
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:
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
catchstatements they respond to.