Ruby PlaygroundRuby Tutorial
UI ThemeDark

Lesson 19 of 23 · Ruby 3.3

Handle an expected failure

Handle a specific exception and separate recovery from cleanup.

Learn

An exception interrupts normal execution. A rescue clause handles matching exception classes so the program can respond to an expected failure. Integer(text) converts suitable text to an integer and raises ArgumentError when the text is invalid.

Use rescue ArgumentError => error when the handler needs the exception object. raise ArgumentError, "message" reports your own invalid input. An else clause runs when the protected code finishes without an exception; ensure runs when leaving it during normal Ruby control flow, including exception propagation. Worker termination is outside this cleanup guarantee.

Example

begin
  value = Integer("not a number")
  puts value * 2
rescue ArgumentError
  puts "Please use digits"
ensure
  puts "Attempt finished"
end

Experiment

  • Predict which parts run. Replace the input with "21" and trace the path through the protected code, rescue and ensure.

  • Predict the recovery message. Change the argument to a positive value and determine whether the method reaches its final expression.

  • Predict the lines that run. Change the text to "bad" and compare else with ensure.

Explore the official manual

Ruby 3.3.3 · Example

Ready to run

Output

Run the code to see what happens.