typestar

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

  1. Subclassing StandardError names a failure precisely.
  2. rescue catches by class and binds the error with =>.
  3. ensure runs on success and failure alike.
  4. The rescue modifier turns a raise into an inline fallback.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Files & errors, step 26 of 29 in Language basics.

← Previous Next →

Exceptions in other languages