0
0
RubyHow-ToBeginner · 3 min read

How to Use Rescue with Specific Exception in Ruby

In Ruby, you can use rescue followed by the specific exception class to catch only that error type. For example, rescue ZeroDivisionError will handle division by zero errors without catching others.
📐

Syntax

The rescue keyword is used inside a begin block to catch exceptions. You specify the exception class after rescue to catch only that type of error. You can also assign the exception object to a variable for more details.

  • begin: Starts the block where errors might happen.
  • rescue ExceptionClass => e: Catches only ExceptionClass errors and stores the error in e.
  • end: Ends the block.
ruby
begin
  # code that might raise an error
rescue SpecificException => e
  # handle the specific exception
end
💻

Example

This example shows how to catch a ZeroDivisionError specifically when dividing by zero. Other errors will not be caught.

ruby
begin
  result = 10 / 0
  puts "Result is #{result}"
rescue ZeroDivisionError => e
  puts "Caught a division by zero error: #{e.message}"
end
Output
Caught a division by zero error: divided by 0
⚠️

Common Pitfalls

One common mistake is rescuing StandardError or no exception class, which catches many errors and can hide bugs. Another is rescuing exceptions without handling them properly, which can make debugging hard.

Always rescue the most specific exception you expect and handle it clearly.

ruby
begin
  # risky code
rescue
  # This rescues all StandardError exceptions, which might hide bugs
  puts "An error occurred"
end

# Better way:
begin
  # risky code
rescue SpecificError => e
  puts "Handled specific error: #{e.message}"
end
📊

Quick Reference

UsageDescription
rescue SpecificExceptionCatches only the specified exception type
rescue SpecificException => eCatches and assigns the exception to variable e
rescueCatches all StandardError exceptions (less specific)
begin ... rescue ... endBasic block to handle exceptions

Key Takeaways

Use rescue with a specific exception class to catch only that error type.
Assign the exception to a variable to access error details.
Avoid rescuing all exceptions to prevent hiding bugs.
Always handle exceptions clearly to aid debugging.