Chapter 12. Exceptions: Handling the Unexpected

In the real world, the unexpected happens. Someone could delete the file your program is trying to load, or the server your program is trying to contact could go down. Your code could check for these exceptional situations, but those checks would be mixed in with the code that handles normal operation. (And that would be a big, unreadable mess.)
This chapter will teach you all about Ruby’s exception handling, which lets you write code to handle the unexpected, and keep it separate from your regular code.
Don’t use method return values for error messages
There’s always a risk that users will make mistakes when calling methods in your code. Take this simple class to simulate an oven, for example. Users create a new instance, call its turn_on method, set its contents attribute to the dish they want to cook (we could only afford a small oven that holds one dish at a time), and then call the bake method to have their dish cooked to a nice golden brown.
But users might forget to turn the oven on before calling bake. They could also call bake while the contents attribute is set to nil. So we’ve built in some error handling for both of those scenarios. Instead of returning the cooked food item, it will return an error string.

If we remember to turn ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access