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 ...
Get Head First Ruby now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.