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.
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 begin…rescue 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
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
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! π
Comments
Post a Comment