Skip to main content

How to Rescue Exceptions in a Whole Ruby Method

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

In Ruby, a method body can have its own rescue, with no begin and end around it. Whatever goes wrong anywhere in the method jumps to that rescue, and the value of its last line becomes the method's return value.

Syntax​

Syntax
def <method>(<arguments>)
<code that might raise>
rescue <ExceptionClass> => <e>
<code that handles it>
end
PartWhat it does
<code that might raise>The method's normal work.
rescue <ExceptionClass>Catches exceptions of that class raised anywhere above it in the method.
=> <e>Puts the exception in a variable, so you can read e.message.
<code that handles it>Runs instead of the rest of the method; its last value is returned.

Ruby's documentation on exceptions: "If you are inside a method, you do not need to use begin or end unless you wish to limit the scope of rescued exceptions".

The Example​

The example has a method that turns text into a number with Integer(), which raises ArgumentError for text that isn't a number. It calls the method with '42' and with 'forty-two', and prints what each call returns with p.

Prerequisites​

  • Ruby. This guide uses Ruby 4.0.10.

Step 1: Write the Code​

Create a file named main.rb:

main.rb, whose parse_age method converts text with Integer, prints the age and returns it, and has a rescue ArgumentError in its body that prints the message and returns nil, called with 42 and with forty-two.

main.rb
def parse_age(text)
age = Integer(text)
puts "Age #{age}"
age
rescue ArgumentError => e
puts "Not a number: #{e.message}"
nil
end

p parse_age('42')
p parse_age('forty-two')

Step 2: Run It​

Terminal
ruby main.rb
Output
Age 42
42
Not a number: invalid value for Integer(): "forty-two"
nil

A zsh terminal where ruby main.rb prints Age 42 and 42, then Not a number: invalid value for Integer(): forty-two, and nil.

The command is the same in zsh, bash and PowerShell.

What Happened​

  • parse_age('42') ran the whole method: it printed Age 42 and returned 42, which p printed.
  • parse_age('forty-two') raised on its first line. Integer() couldn't read the text, so Ruby skipped the rest of the method and jumped to rescue.
  • The rescue printed the message and returned nil, its last value, which p printed.

Common Mistakes​

MistakeWhat happensDo this instead
Writing rescue with no classIt catches every StandardError, including bugs you'd want to seeName the class you expect, such as ArgumentError
Forgetting what the rescue returnsThe method returns the rescue's last value, often nil from putsEnd the rescue with the value you want returned
Rescuing in the method when only one line can failErrors from other lines are caught tooWrap just that line in begin ... rescue ... end

Troubleshooting​

SymptomLikely causeFix
The exception isn't caughtIt's a different class than the one after rescueRescue its class, or a parent class
The method returns nil unexpectedlyThe rescue ran, and its last line was putsCheck the output for the rescue's message

FAQ​

Can I add ensure too?​

Yes. An ensure after the rescue, still inside the method, runs whether or not an exception happened.

Does this work in blocks?​

Yes, the documentation says "The same is true for a class, module, and block".

Conclusion​

Put rescue straight into a method body to handle an exception from anywhere in the method, without begin and end. Its last value becomes the method's return value.

Additional Resources​