4 Handling error without exceptions

 

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.

4.1  The good and bad aspects of exceptions

4.2  Possible alternatives to exceptions

4.2.1  Sentinel value

4.2.2  Supplied default value

4.3  Encoding success conditions with Option

4.3.1  Usage patterns for Option

4.3.2  Option composition, lifting, and wrapping exception-oriented APIs

4.4  Encoding success and failure conditions with Either

4.5  Summary

sitemap