97 Things Every Programmer Should Know

(Chris Devlin) #1

Collective Wisdom from the Experts 43

A different, but still technical, situation is when the program cannot proceed
because of a problem in the execution environment, such as an unresponsive
database. In this situation, you must assume that the infrastructure did what it
could to resolve the issue—repairing connections and retrying a reasonable num-
ber of times—and failed. Even if the cause is different, the situation for the calling
code is similar: there is little it can do about it. So, we signal the situation through
an exception that we let bubble up to the general exception-handling mechanism.

In contrast to these, we have the situation where you cannot complete the call
for a domain-logical reason. In this case, we have encountered a situation that
is an exception, i.e., unusual and undesirable, but not bizarre or programmati-
cally in error (for example, if I try to withdraw money from an account with
insufficient funds). In other words, this kind of situation is a part of the con-
tract, and throwing an exception is just an alternative return path that is part
of the model and that the client should be aware of and be prepared to handle.
For these situations, it is appropriate to create a specific exception or a separate
exception hierarchy so that the client can handle the situation on its own terms.

Mixing technical exceptions and business exceptions in the same hierarchy
blurs the distinction and confuses the caller about what the method contract
is, what conditions it is required to ensure before calling, and what situations
it is supposed to handle. Separating the cases gives clarity and increases
the chances that technical exceptions will be handled by some application
framework, while the business domain exceptions actually are considered
and handled by the client code.

Free download pdf