Error Handling in Ruby — Don’t Panic, Rescue!

Error Handling in Ruby — Don’t Panic, Rescue!

🚨 Error Handling in Ruby — Don’t Panic, Rescue! πŸš€

For students, freshers, and curious devs who want to survive Ruby's "uh-oh" moments.

Let’s face it — coding without errors is like making Maggi without spilling a little masala. Impossible! 😜 So instead of throwing your laptop out of the window when Ruby screams at you, let’s learn to *rescue* our code like true heroes.

Mini Story: Imagine you’re writing the next big Ruby app. Everything is going fine until suddenly…
undefined method `sizee' for nil:NilClass (NoMethodError)
That’s Ruby’s polite way of saying: “Yo, you messed up.” But instead of crying, we’ll put on our superhero cape and *rescue* the situation.

1. Meet begin and rescue — Your New Besties 🀝

Ruby gives us the beginrescue block to handle errors like a pro. Think of it as Ruby saying: “Try this. If it explodes, I got you.”

begin
  number = 10 / 0
  puts "Math is easy!"
rescue ZeroDivisionError => e
  puts "Oops! You tried dividing by zero."
  puts "Ruby says: #{e.message}"
end
    

Output:

Oops! You tried dividing by zero.
Ruby says: divided by 0
πŸ’‘ Tip: Always rescue specific errors like ZeroDivisionError instead of rescuing everything — or you’ll hide real bugs!

2. Handling Different Errors Like a Boss πŸ•Ά️

Sometimes multiple disasters can happen. Ruby lets you prepare for each one:

begin
  file = File.open("secret.txt")
  puts file.read
rescue Errno::ENOENT
  puts "File not found! Did you forget to create it?"
rescue => e
  puts "Something else broke: #{e.message}"
end
    

3. ensure — The Cleanup Crew 🧹

No matter what happens, ensure will run. Perfect for closing files, disconnecting databases, or just saying goodbye politely.

begin
  file = File.open("data.txt")
  puts file.read
rescue
  puts "Oops! Couldn’t read the file."
ensure
  file.close if file
  puts "File closed. πŸ—„️"
end
    

4. The Danger of Lazy Rescues ⚠️

Rescuing without knowing what you’re rescuing is like catching all animals with one net — You’ll catch the fish, but also the angry crocodile. 🐊

# ❌ Don't do this
begin
  risky_operation
rescue
  puts "Something went wrong."
end
    
✅ Instead: Rescue specific errors, so you know what went wrong and why.

5. Quick Recap πŸ“š

  • Errors aren’t evil — they’re clues.
  • begin + rescue = Safety net for your code.
  • ensure = Always runs, no matter what.
  • Be specific with rescues. Don’t hide bugs under the carpet.
  • Laugh at your mistakes — they make you a better coder!

So the next time Ruby throws a tantrum, don’t panic — rescue it! 🦸‍♀️ Happy coding, future Ruby ninjas! πŸ’Ž

© 2025 Ruby Dev Tales | Crafted with ❤️ for students & devs

Comments

Popular posts from this blog

Why Every Developer Should Meet Ruby: A Friendly Introduction

This is Ruby. And Ruby knows how to block — like a bouncer for bad code. πŸ”₯

Iterators in Ruby — Think Less Looping, More Logic