Challenge - 5 Problems
Ruby Rescue Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of multiple rescue clauses with different exceptions
What is the output of this Ruby code with multiple rescue clauses?
Ruby
begin 1 / 0 rescue ZeroDivisionError puts "ZeroDivisionError caught" rescue StandardError puts "StandardError caught" end
Attempts:
2 left
💡 Hint
Think about which error is raised by dividing by zero in Ruby.
✗ Incorrect
Dividing by zero raises a ZeroDivisionError, so the first rescue clause matches and prints "ZeroDivisionError caught".
❓ Predict Output
intermediate2:00remaining
Which rescue clause handles the exception?
What will this Ruby code print?
Ruby
begin [].fetch(10) rescue IndexError puts "IndexError handled" rescue KeyError puts "KeyError handled" end
Attempts:
2 left
💡 Hint
Check what exception is raised when fetching an invalid index from an array.
✗ Incorrect
Calling fetch with an invalid index raises IndexError, so the first rescue clause runs.
❓ Predict Output
advanced2:00remaining
Output when multiple exceptions are rescued with one clause
What does this Ruby code output?
Ruby
begin {}.fetch(:foo) rescue KeyError, NoMethodError puts "KeyError or NoMethodError rescued" rescue StandardError puts "StandardError rescued" end
Attempts:
2 left
💡 Hint
Accessing a missing key in a hash with [] returns nil, but with fetch it raises KeyError.
✗ Incorrect
Hash#fetch raises KeyError for missing keys, so the first rescue clause matches and prints "KeyError or NoMethodError rescued".
❓ Predict Output
advanced2:00remaining
Which rescue clause runs with nested exceptions?
What will this Ruby code print?
Ruby
begin begin raise ArgumentError, "wrong argument" rescue TypeError puts "TypeError rescued" end rescue ArgumentError puts "ArgumentError rescued" end
Attempts:
2 left
💡 Hint
The inner rescue only catches TypeError, but the raised error is ArgumentError.
✗ Incorrect
The inner rescue does not catch ArgumentError, so it propagates to the outer rescue which catches ArgumentError and prints "ArgumentError rescued".
❓ Predict Output
expert2:00remaining
Output of multiple rescue clauses with else and ensure
What is the output of this Ruby code?
Ruby
begin puts "Start" 10 / 2 rescue ZeroDivisionError puts "ZeroDivisionError caught" rescue StandardError puts "StandardError caught" else puts "No errors" ensure puts "Always runs" end
Attempts:
2 left
💡 Hint
The else clause runs only if no exception is raised.
✗ Incorrect
The division 10 / 2 does not raise an error, so the else clause runs printing "No errors". The ensure clause always runs printing "Always runs".