0
0
Rubyprogramming~20 mins

Multiple rescue clauses in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Rescue Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
AStandardError caught
BZeroDivisionError caught
CNo output, program crashes
DRuntimeError caught
Attempts:
2 left
💡 Hint
Think about which error is raised by dividing by zero in Ruby.
Predict Output
intermediate
2: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
AKeyError handled
BArgumentError handled
CNo output, program crashes
DIndexError handled
Attempts:
2 left
💡 Hint
Check what exception is raised when fetching an invalid index from an array.
Predict Output
advanced
2: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
AKeyError or NoMethodError rescued
BStandardError rescued
CNo output, program crashes
DTypeError rescued
Attempts:
2 left
💡 Hint
Accessing a missing key in a hash with [] returns nil, but with fetch it raises KeyError.
Predict Output
advanced
2: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
ANo output, program crashes
BTypeError rescued
CArgumentError rescued
DRuntimeError rescued
Attempts:
2 left
💡 Hint
The inner rescue only catches TypeError, but the raised error is ArgumentError.
Predict Output
expert
2: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
A
Start
No errors
Always runs
B
Start
ZeroDivisionError caught
Always runs
C
Start
Always runs
D
Start
StandardError caught
Always runs
Attempts:
2 left
💡 Hint
The else clause runs only if no exception is raised.