How to Rescue a Specific Exception in Ruby
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
begin
<code that may raise>
rescue <ExceptionClass> => <e>
<handle it, for example with <e>.message>
end
| Part | What it does |
|---|---|
begin ... end | Marks 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:

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
ruby main.rb
42
Not a number: invalid value for Integer(): "forty-two"
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
| Mistake | What happens | Do this instead |
|---|---|---|
| No rescue around code that can fail | invalid value for Integer(): "forty-two" (ArgumentError) stops the script | Rescue the class where you can handle it |
A bare rescue around a lot of code | Unrelated bugs are swallowed | Rescue the specific class |
Rescuing Exception | Also catches signals such as interrupts | Rescue StandardError subclasses |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| The script still stops with an error | The raised class isn't the one rescued | Read the class in brackets at the end of the error line |
| Errors disappear silently | A rescue block does nothing | Print 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
- Exception handling, in the Ruby documentation.
