0
0
Rubyprogramming~5 mins

Rescue modifier (inline form) in Ruby

Choose your learning style9 modes available
Introduction

The rescue modifier lets you handle errors quickly in one line. It helps keep your code simple and clean when you expect something might fail.

When you want to try a quick operation but have a simple fallback if it fails.
When reading a file that might not exist and you want to use a default value instead.
When converting user input to a number but want to avoid crashing if input is bad.
When calling a method that might raise an error and you want to continue smoothly.
Syntax
Ruby
expression rescue fallback_value

The code tries to run expression.

If an error happens, it returns fallback_value instead.

Examples
This tries to divide 10 by 0, which causes an error. Instead of crashing, it returns the string.
Ruby
result = 10 / 0 rescue 'Cannot divide by zero'
Calling upcase on nil causes an error, so it prints the fallback string.
Ruby
name = nil
puts (name.upcase rescue 'No name given')
Trying to convert 'abc' to an integer fails, so it returns 0 instead.
Ruby
number = Integer('abc') rescue 0
Sample Program

This program defines a method that divides two numbers. If dividing by zero happens, it returns an error message instead of crashing.

Ruby
def safe_divide(a, b)
  a / b rescue 'Error: division by zero'
end

puts safe_divide(10, 2)
puts safe_divide(10, 0)
OutputSuccess
Important Notes

The rescue modifier only catches StandardError and its subclasses.

Use it for simple error handling, but for complex cases, use full begin...rescue blocks.

Summary

The rescue modifier helps handle errors in one line.

It tries the expression and returns a fallback if an error occurs.

Great for simple, quick error handling without extra code.