Skip to main content

How to Rescue a Specific Exception in Ruby

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

When something fails in Ruby, it raises an exception, and the script stops unless something rescues it. Naming the exception's class after rescue handles the failure you expected and lets every other error through.

Syntax​

Syntax
begin
<code that may raise>
rescue <ExceptionClass> => <e>
<handle it, for example with <e>.message>
end
PartWhat it does
begin ... endMarks the code to protect. Inside a method, the method body works the same, without begin.
rescue <ExceptionClass>Handles that class and its subclasses.
=> <e>Puts the exception in a variable; e.message is its text.

The Ruby exceptions documentation: "Exceptions are rescued in a begin/end block". It adds: "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 converts text to a number with Integer(). For forty-two that raises an ArgumentError, which the method rescues, reports and replaces with 0.

Prerequisites​

  • Ruby. This guide uses Ruby 4.0.10.

Step 1: Write the Code​

Create a file named main.rb:

main.rb, which defines to_number(text) returning Integer(text), rescues ArgumentError as e by putting Not a number: with the message and returning 0, and puts to_number('42') and to_number('forty-two').

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

puts to_number('42')
puts to_number('forty-two')

The rescue sits at the method's level, so the whole method body is protected without begin.

Step 2: Run It​

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

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

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

What a Bare rescue Catches​

The documentation: "By default, StandardError and its subclasses are rescued." ArgumentError is a StandardError, so a bare rescue caught it too. Bare rescue is broad: it also hides bugs such as a NoMethodError, so name the class you expect.

Common Mistakes​

MistakeWhat happensDo this instead
No rescue around code that can failinvalid value for Integer(): "forty-two" (ArgumentError) stops the scriptRescue the class where you can handle it
A bare rescue around a lot of codeUnrelated bugs are swallowedRescue the specific class
Rescuing ExceptionAlso catches signals such as interruptsRescue StandardError subclasses

Troubleshooting​

SymptomLikely causeFix
The script still stops with an errorThe raised class isn't the one rescuedRead the class in brackets at the end of the error line
Errors disappear silentlyA rescue block does nothingPrint or log e.message

FAQ​

Can one rescue handle several classes?​

Yes: rescue ArgumentError, TypeError => e.

Is there an ensure block?​

Yes. Code under ensure runs whether or not an exception was raised.

Conclusion​

rescue SomeError => e handles one kind of failure and gives you e.message; everything else keeps going up. Inside a method, the rescue can sit directly in the method body.

Additional Resources​