12.2. Exception Throwing

The other major camp is that of the exception throwers. Many modern languages have some notion of exceptions, which can be thrown and caught. In an exception-aware model, every method can be assumed to succeed unless it throws an exception, so it isn't necessary to check for the success case. Even among exception throwers there is dissent, however. Not everyone accepts this vision of how exceptions should be used. Some feel that exceptions should only be thrown in an "exceptional" situation. I disagree. As mentioned previously, I favor the use of noun-verb naming conventions, wherein domain objects are nouns, and methods that act upon those objects are verbs. Those verb-oriented method names represent a contract, and any violation of that contract should cause an exception. To once again use a banking example, a method called TransferFunds should in fact transfer funds from one place to another. If it cannot fulfill that contract — for any reason — it should throw an exception indicating its failure to do so.

There is no reason why exceptions should be reserved for "exceptional" cases. Determining which cases are truly exceptional is far too subjective to be used as policy. It is much easier to simply think about contracts and the fulfillment of those contracts. You can assume that the advertised contract will be fulfilled, and then deal with exceptions if they should happen to come up. This makes for a much simpler programming model. The following code ...

Get Code Leader: Using People, Tools, and Processes to Build Successful Software now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.