Menu
Coddy logo textTech

Multiple rescue Clauses

Part of the Logic & Flow section of Coddy's Ruby journey — lesson 45 of 56.

One begin block can have several rescue clauses. Ruby checks them top to bottom and runs the first one whose exception class matches.

begin
  number = Integer(gets.chomp)
  result = 100 / number
  puts result
rescue ArgumentError
  puts "That's not a valid number."
rescue ZeroDivisionError
  puts "Can't divide by zero."
end

Order matters: list specific classes before general ones. StandardError placed first would swallow everything and the later branches would never run.

You can also catch multiple exception classes in one branch by listing them with commas:

begin
  risky_call
rescue ArgumentError, TypeError => e
  puts "Bad input: #{e.message}"
end

Use this when the recovery code is the same for several failure modes.

challenge icon

Challenge

Easy

Read two lines from input, both meant to be integers. Use Integer(...) for both, then divide the first by the second.

Handle three cases with separate rescue branches:

  • ArgumentError → print Bad number!
  • ZeroDivisionError → print Cannot divide by zero!
  • TypeError → print Wrong type!

If everything works, print Result: <a / b> (integer division).

For input 10 / 2, the output is Result: 5. For 10 / 0, Cannot divide by zero!. For 10 / abc, Bad number!.

Cheat sheet

A begin block can have multiple rescue clauses — Ruby matches them top to bottom:

begin
  number = Integer(gets.chomp)
  result = 100 / number
  puts result
rescue ArgumentError
  puts "That's not a valid number."
rescue ZeroDivisionError
  puts "Can't divide by zero."
end

List specific exception classes before general ones — a general class like StandardError placed first would swallow all subsequent branches.

Catch multiple exception classes in one branch by separating them with commas:

rescue ArgumentError, TypeError => e
  puts "Bad input: #{e.message}"

Try it yourself

raw_a = gets.chomp
raw_b = gets.chomp

# TODO: begin ... rescue ArgumentError ... rescue ZeroDivisionError ... rescue TypeError ... end
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow