Skip to content
Raising and Rescuing
step 1/6

Reading — step 1 of 6

Learn

~1 min readExceptions and Enumerable

Raise an exception with raise:

raise "something failed"                           # raises RuntimeError
raise ArgumentError, "bad input"                   # specific class + message
raise ValidationError.new("missing field: email")  # custom class

Rescue with begin/rescue/ensure/end:

begin
  parse_config(input)
rescue JSON::ParserError => e
  warn "bad json: #{e.message}"
rescue StandardError => e
  warn "unexpected: #{e.message}"
  raise        # re-raise
ensure
  cleanup()    # always runs
end

rescue clause on method body — shortcut without explicit begin:

def safe_parse(s)
  Integer(s)
rescue ArgumentError
  nil
end

Custom exception classes:

class ValidationError < StandardError
  def initialize(field)
    super("missing field: #{field}")
    @field = field
  end
  attr_reader :field
end

begin
  raise ValidationError.new("email")
rescue ValidationError => e
  puts "missing: #{e.field}"
end

The hierarchy — by convention all custom exceptions inherit from StandardError (not Exception directly). A bare rescue catches StandardError and its descendants but NOT system-level things like Interrupt or SystemExit.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…