๐ŸŽ“ A1Learner
๐Ÿ”
0 of 34 lessons completed

Ruby Custom Errors

A program can make its own error class with a name that fits its job. A custom name makes a failure easy to spot and easy to catch.

Defining and raising a custom error

The class line makes TooYoungError as a new kind of error. raise starts the error with a message, and the rescue line catches it by name.

class TooYoungError < StandardError
end
begin
  raise TooYoungError, "You must be 18 or older"
rescue TooYoungError => e
  puts e.message
end

Raising from inside a method

The check_age method raises the custom error when the age is under 18. The rescue line prints the class name and the message.

class TooYoungError < StandardError
end
def check_age(age)
  if age < 18
    raise TooYoungError, "Too young"
  end
  puts "Welcome"
end
begin
  check_age(15)
rescue TooYoungError => e
  puts e.class
  puts e.message
end

Raising with no message

raise can start a custom error with no message text. The message then reads as the class name itself.

class EmptyCartError < StandardError
end
begin
  raise EmptyCartError
rescue EmptyCartError => e
  puts e.class
  puts e.message
end

An error carrying a stored value

LimitError stores the amount it was built with. The rescue line reads the message and the stored amount back.

class LimitError < StandardError
  def initialize(amount)
    super("Over the limit")
    @amount = amount
  end
  def amount
    @amount
  end
end
begin
  raise LimitError.new(250)
rescue LimitError => e
  puts e.message
  puts e.amount
end

Example

class TooYoungError < StandardError
end
def enter(age)
  if age < 18
    raise TooYoungError, "Entry needs 18 plus"
  end
  puts "Entered"
end
begin
  enter(21)
  enter(16)
rescue TooYoungError => e
  puts e.message
end

Key points

  • A class line with < StandardError makes a new error class.
  • raise with the class name raises an error of that class.
  • raise can carry a message text along with the class.
  • rescue can name the custom class like any other class.
  • An error object can store a value in an instance variable.
  • A plain method can hand the stored value back to the rescue line.

In this example, the enter method raises TooYoungError for any age under 18. The first call with 21 prints Entered, and the second call with 16 raises the error. The rescue line catches it by its custom name and prints the message.

Note

A custom error still answers e.class with its name and e.message with its text.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the line class GateError < StandardError do?