Handling Errors

In this chapter, we will continue working on the retirement calculator that we implemented in Chapter 2, Developing a Retirement Calculator. Our calculator worked correctly as long as we passed the right arguments, but would fail badly with a horrible stack trace if any of the parameters were wrong. Our program only worked for what we call the happy path.

The reality of writing production software is that all kinds of error scenarios can occur. Some of them are recoverable, some of them must be presented to the user in an attractive way, and, for some hardware-related errors, we might need to let the program crash.

In this chapter, we will introduce exception handling, explain what referential transparency is, and try to convince you that exceptions are not the best way to deal with errors. Then, we will explain how to use functional programming constructs to effectively handle the possibility of an error.

In each section, we will briefly introduce a new concept, and then use it in a Scala worksheet to get a sense of how to use it. After that, we will apply this new knowledge to improve the retirement calculator.

In this chapter, we will look at the following topics:

  • Using exceptions when necessary
  • Understanding referential transparency
  • Using Option to represent optional values
  • Using Either to handle errors sequentially
  • Using Validated to handle errors in parallel
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset