Challenge - 5 Problems
Ruby Rescue Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Ruby code using rescue?
Look at this Ruby code. What will it print when run?
Ruby
def divide(a, b) a / b rescue ZeroDivisionError "Cannot divide by zero" end puts divide(10, 0)
Attempts:
2 left
💡 Hint
Think about what happens when you divide by zero in Ruby and how rescue handles it.
✗ Incorrect
The code tries to divide 10 by 0, which causes a ZeroDivisionError. The rescue block catches this error and returns the string "Cannot divide by zero" instead of crashing.
🧠 Conceptual
intermediate1:30remaining
Why do we use rescue in Ruby error handling?
Choose the best reason why Ruby uses rescue for error handling.
Attempts:
2 left
💡 Hint
Think about what happens if an error is not handled in a program.
✗ Incorrect
Rescue is used to catch errors and handle them gracefully, so the program does not crash and can continue running or provide a helpful message.
🔧 Debug
advanced2:00remaining
What error does this Ruby code raise?
This code tries to open a file and read it. What error will it raise?
Ruby
def read_file(filename) File.open(filename) do |file| file.read end rescue "File not found" end puts read_file("missing.txt")
Attempts:
2 left
💡 Hint
Check Ruby's error class for missing files.
✗ Incorrect
Ruby raises Errno::ENOENT when a file is missing. The rescue block catches this error and returns "File not found".
❓ Predict Output
advanced2:30remaining
What is the output of this nested rescue example?
What will this Ruby code print?
Ruby
def test begin raise "Oops" rescue RuntimeError begin raise "Inner error" rescue "Handled inner" end end end puts test
Attempts:
2 left
💡 Hint
Look at how the inner rescue handles the second raise.
✗ Incorrect
The outer begin raises "Oops" which is rescued. Inside that rescue, another error "Inner error" is raised and rescued, returning "Handled inner".
🚀 Application
expert3:00remaining
How many times will the rescue block run in this code?
Count how many times the rescue block executes in this Ruby code.
Ruby
count = 0 3.times do |i| begin raise "Error at #{i}" if i.even? rescue count += 1 end end puts count
Attempts:
2 left
💡 Hint
Check which values of i are even in the loop.
✗ Incorrect
The loop runs 3 times with i = 0,1,2. Errors are raised only when i is even (0 and 2), so rescue runs twice.