0
0
Rubyprogramming~3 mins

Why error handling uses rescue in Ruby - The Real Reasons

Choose your learning style9 modes available
The Big Idea

What if your program could fix its own mistakes without crashing?

The Scenario

Imagine you are writing a program that reads a file and processes its content. Without error handling, if the file is missing or unreadable, the program just crashes and stops working.

The Problem

Manually checking every possible error before each operation is slow and messy. It makes the code long and hard to read. Plus, you might miss some errors, causing unexpected crashes.

The Solution

The rescue keyword in Ruby lets you catch errors when they happen and handle them smoothly. This keeps your program running and lets you decide what to do next, like showing a friendly message or trying a backup plan.

Before vs After
Before
if File.exist?(filename)
  content = File.read(filename)
else
  puts 'File not found'
end
After
begin
  content = File.read(filename)
rescue Errno::ENOENT
  puts 'File not found'
end
What It Enables

It enables your program to keep working safely even when unexpected problems happen.

Real Life Example

When a website tries to load user data but the database is down, rescue helps show a helpful error message instead of a broken page.

Key Takeaways

Manual error checks make code long and fragile.

rescue catches errors cleanly and keeps programs running.

This makes your code easier to read and more reliable.