Exceptions in Ruby
raise, rescue, ensure and a custom error class of your own.
class EmptyCartError < StandardError; end
def checkout(items)
raise EmptyCartError, "nothing to buy" if items.empty?
items.sum
end
begin
puts checkout([5, 8])
puts checkout([])
rescue EmptyCartError => e
puts "refused: #{e.message}"
ensure
puts "till closed"
end
# rescue as a modifier turns a raise into an inline fallback
puts (Integer("nope") rescue "not a number")
How it works
- Subclassing
StandardErrornames a failure precisely. rescuecatches by class and binds the error with=>.ensureruns on success and failure alike.- The
rescuemodifier turns a raise into an inline fallback.
Keywords and builtins used here
EmptyCartErrorIntegerbegincheckoutclassdefendensureifputsraiserescue
The run, in numbers
- Lines
- 18
- Characters to type
- 371
- Tokens
- 75
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 53 seconds.
Step 2 of 3 in Files & errors, step 26 of 29 in Language basics.