Menu
Coddy logo textTech

begin / rescue

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

To stop an exception from crashing your program, wrap the risky code in begin ... rescue ... end. If anything inside begin raises, Ruby jumps to the matching rescue block instead of aborting.

begin
  result = 10 / 0
  puts result
rescue ZeroDivisionError
  puts "Cannot divide by zero!"
end
# Cannot divide by zero!

You can grab the exception object itself with => e and read its .message:

begin
  Integer("hello")
rescue ArgumentError => e
  puts "Bad input: #{e.message}"
end
# Bad input: invalid value for Integer(): "hello"

If you don't name an exception class, rescue on its own catches StandardError and its descendants, most everyday failures. Catching is most useful when you can do something in the rescue block: substitute a default value, log the problem, ask the user again.

challenge icon

Challenge

Easy

Read two lines from input, both should be integers, but the second one might not be a valid number.

Wrap the parsing of the second line in begin / rescue:

  • Use Integer(input) (which raises ArgumentError on a bad string)
  • If parsing succeeds, print Sum: <a + b>
  • If it fails, print Bad number!

For input 3 then 4, the output is Sum: 7. For 3 then abc, it's Bad number!.

Cheat sheet

Use begin ... rescue ... end to handle exceptions without crashing:

begin
  result = 10 / 0
rescue ZeroDivisionError
  puts "Cannot divide by zero!"
end

Capture the exception object with => e to access its message:

begin
  Integer("hello")
rescue ArgumentError => e
  puts "Bad input: #{e.message}"
end

Using rescue without a class catches StandardError and its descendants.

Try it yourself

a = gets.to_i
raw_b = gets.chomp

# TODO: begin/rescue around Integer(raw_b); print sum or "Bad number!"
quiz iconTest yourself

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

All lessons in Logic & Flow