Colocate Exceptions

by kirk knoernschild

Statement

Exceptions should be close to the class or interface that throw them.

Description

Sadly, dealing with exceptions in enterprise software systems is often an afterthought. But allocation of exceptions to modules has significant implications on the modularity, and more specifically the dependencies between modules, within our software system. Placing the exception close to a class that catches it will often cause a cyclic dependency between the module containing the class that throws the exception and the module containing the class that catches the exception. Exceptions should always be placed in a module closer to the class that throws the exception than a module closer to the class that catches the exception. Figure 1 illustrates this scenario.

ColocateExceptions

Figure 1: Colocate Exceptions

Implementation Variations

Whereas separate abstractions says that interfaces should be close to the classes that use them, exceptions should be close to the class that throws them.

If multiple classes from separate modules throw the same exception, the demotion should be used to manage the dependencies between the two modules.

Similar to separate abstractions – that is where we place the interface.

Consequences

Sample Code

Wrapping Up