Catching errors: rescue
In lesson 28 every error stopped the program, and you repaired the code. But some errors aren't the code's fault at all – they come from what comes in: someone types “bacon” where a number belongs. Ruby knows two ways of turning text into a number. to_i is the quiet one: it reads digits for as long as it finds any, and otherwise simply returns 0. Integer(…) is the strict one:
p "42".to_i
p "12 strips".to_i
p "bacon".to_i
Integer("42")“12 strips” quietly becomes 12, “bacon” quietly becomes 0 – handy sometimes, often a lie: did the fox really eat 0 strips, or did it mistype? Integer only accepts text that is a number through and through. Anything else, it reports out loud:
Integer("bacon")ArgumentError: invalid value for Integer(): "bacon" – good to know! Only, the error stops the whole program. To keep it running, you catch the error: code that may go wrong goes between begin and rescue; after rescue comes which error you mean, and below it what should happen then:
begin
number = Integer("bacon")
puts "A number: #{number}"
rescue ArgumentError
puts "That was no number."
end
puts "And on we go!"Step through the cell with ⏯: Integer raises the error, and Ruby jumps straight to the rescue – the puts with the number never gets its turn. After the end, the program carries on as normal. With => e you get hold of the error itself: e.class is its kind, e.message its message. And since different things can go wrong, there may be several rescues – Ruby takes the first one that fits. Twelve strips, shared out fairly:
["4", "bacon", "0"].each do |input|
begin
foxes = Integer(input)
puts "#{foxes} foxes: #{12 / foxes} strips each"
rescue ArgumentError => e
puts "#{e.class}: #{e.message}"
rescue ZeroDivisionError
puts "Zero foxes? Then Chunky eats them all!"
end
endYou can raise errors yourself, too, with raise: the error class, a comma, your message. That pays off when your method can't do anything with a value – better loud right away than a puzzling result later. Chunky's bacon stall sells at least one strip:
def order_strips(count)
raise ArgumentError, "at least 1, not #{count}" if count < 1
"#{count} strips of bacon, coming right up!"
end
p order_strips(3)
order_strips(-2)There it is, your own ArgumentError with your own message – red like Ruby's, and right at the spot where the wrong value came in. Catching it works as before, and inside a method you don't even need begin: a rescue right in the method body catches whatever goes wrong in the method before it. Two helpers join in: else runs only when no error came, and ensure always runs at the end, with an error or without – the right place for tidying up:
def take_order(text)
count = Integer(text)
raise ArgumentError, "at least 1, not #{count}" if count < 1
rescue ArgumentError => e
"Sorry, no: #{e.message}"
else
"#{count} strips of bacon, coming right up!"
ensure
puts "(Chunky notes: #{text})"
end
puts take_order("3")
puts take_order("0")
puts take_order("lots")Step through the three orders with ⏯ and watch the order of things: Chunky's note appears before the answer every time. ensure runs while the method is returning – before puts even gets its result. It doesn't change the return value, though: that comes from the rescue when an error came, otherwise from the else.
Sometimes it helps simply to try again. retry in the rescue jumps back to the start of begin. So that it doesn't go on forever, you count along:
inputs = ["bacon", "four", "4"] # typed in one after the other
attempts = 0
begin
attempts += 1
number = Integer(inputs[attempts - 1])
rescue ArgumentError
puts "Attempt #{attempts}: not a number, again!"
retry if attempts < 3
end
"#{number} after #{attempts} attempts"Without the if attempts < 3, an error that comes back every time would make retry try forever. So a retry always needs a limit.
And if all you want is a number or nil, without any error? For this common case Integer and Float have a shortcut, exception: false:
p Integer("42", exception: false)
p Integer("bacon", exception: false)
Float("4.5", exception: false)A rule of thumb: catch only the errors you expect and can do something sensible about – rescue ArgumentError, not a bare rescue. A bare rescue catches almost everything, including the NoMethodError of your typo, and then you hunt for it for hours. And a method that can't do anything with a value says so with raise – whoever calls it decides whether to catch the error. Error classes of your own come later, in lesson 115.
number_or_nil(text): it returns the number in the text ("42" → 42), and if the text isn't a whole number, it catches Integer's error with rescue and returns nil. Use it to add up the real numbers on the notes in total.notes = ["3", "three", "4", "", "2"]
# def number_or_nil(text)
# ... # the number in the text - or nil on an ArgumentError
# end
# total = ... # the real numbers on the notes, added upread_strips(text) turns the text into a number with Integer and raises an ArgumentError itself, with the message "too much bacon: 50", when it's more than 10 – it doesn't catch anything. take_orders(texts) calls it for every text and returns an array: the number, or – when read_strips raises an error – its message. take_orders(["3", "50", "bacon"]) gives [3, "too much bacon: 50", "invalid value for Integer(): \"bacon\""].# def read_strips(text)
# ... # the number; over 10: ArgumentError "too much bacon: 50"
# end
# def take_orders(texts)
# ... # for every text the number - or the error's message
# end
# take_orders(["3", "50", "bacon"])