0
0
Rubyprogramming~3 mins

Why Rescue modifier (inline form) in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could stop your program from crashing with just a tiny addition to your code?

The Scenario

Imagine you have a program that tries to divide numbers, but sometimes the divisor might be zero. Without a quick way to handle errors, your program crashes and stops working.

The Problem

Manually writing full error handling blocks everywhere makes your code long and hard to read. It's easy to forget to handle some errors, and the program can break unexpectedly.

The Solution

The rescue modifier lets you handle errors right where they happen, in a short and clear way. It keeps your code clean and prevents crashes by providing a quick fallback value.

Before vs After
Before
begin
  result = 10 / divisor
rescue ZeroDivisionError
  result = 0
end
After
result = 10 / divisor rescue 0
What It Enables

You can write safer, simpler code that keeps running smoothly even when unexpected errors happen.

Real Life Example

When reading user input that might be empty or invalid, you can quickly provide a default value without stopping the whole program.

Key Takeaways

Manual error handling can be long and repetitive.

Rescue modifier handles errors inline, making code shorter and clearer.

It helps programs keep running smoothly by providing quick fallback values.