4 Handling errors without exceptions

 

This chapter covers

  • Pitfalls of throwing exceptions
  • Understanding why exceptions break referential transparency
  • Handling exceptional cases: a functional approach
  • Using Option to encode success and ignore failure
  • Applying Either to encode successes and failures

We noted briefly in chapter 1 that throwing an exception is a side effect and an undesired behavior. But why do we consider throwing exceptions bad? Why is it not the 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 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 problems with throwing exceptions

4.2 Problematic 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.3.3 For-comprehensions with Option

4.4 Encoding success and failure conditions with Either

4.4.1 For-comprehensions with Either

Summary

sitemap