This chapter covers:
- Understanding the pitfalls of throwing exceptions, and why they break referential transparency
- Adopting a pure functional approach for handling exceptional cases
- Using the
Option
data type to encode success conditions and ignore failures
- Applying the
Either
data type to encode both success and failure conditions
We noted briefly in chapter 1 that throwing an exception is a side effect, and is undesired behaviour. But why do we consider throwing exceptions bad? Why is it not a desired effect? The answer has much to do with a loss of control. At the point that an exception is thrown, control is delegated away from the program, and the exception is propagated up the call stack. This loss of control means one of two things—the program will be terminated because the exception was not handled, or else some part of the program higher up on the call stack will catch and deal with the exception. The complexity of our program has just escalated dramatically, and in functional programming this loss of control and additional complexity should be avoided at all costs.