0
0
Rubyprogramming~3 mins

Why Multiple rescue clauses in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could catch every problem your program faces without messy code everywhere?

The Scenario

Imagine you write a program that talks to a website, reads a file, and does some math. Sometimes things go wrong: the website might be down, the file might be missing, or the math might try to divide by zero. If you try to fix each problem one by one by writing separate code everywhere, it quickly becomes messy and confusing.

The Problem

Handling each error manually means repeating similar code many times. It's easy to forget some errors or mix up fixes. Your program becomes long, hard to read, and full of mistakes. Fixing one error might break another part. It's like trying to fix a leaky roof by patching every hole separately without a plan.

The Solution

Multiple rescue clauses let you catch different errors in one place, each with its own fix. This keeps your code clean and organized. You can handle each problem clearly and separately, making your program easier to understand and maintain.

Before vs After
Before
begin
  # file risky code
rescue IOError
  puts 'File error'
end

begin
  # math risky code
rescue ZeroDivisionError
  puts 'Math error'
end
After
begin
  # risky code
rescue IOError
  puts 'File error'
rescue ZeroDivisionError
  puts 'Math error'
end
What It Enables

You can write safer programs that handle many different problems clearly and keep running smoothly.

Real Life Example

Think of a cashier machine that can run out of paper, lose internet, or get wrong input. Multiple rescue clauses help the machine handle each problem properly without crashing.

Key Takeaways

Manual error handling is repetitive and messy.

Multiple rescue clauses organize error fixes by type.

This makes code clearer, safer, and easier to maintain.