0
0
Rubyprogramming~20 mins

Why error handling uses rescue in Ruby - Challenge Your Understanding

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
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)
ACannot divide by zero
B0
C10
DZeroDivisionError
Attempts:
2 left
💡 Hint
Think about what happens when you divide by zero in Ruby and how rescue handles it.
🧠 Conceptual
intermediate
1:30remaining
Why do we use rescue in Ruby error handling?
Choose the best reason why Ruby uses rescue for error handling.
ATo automatically fix all errors without programmer input
BTo catch and handle errors so the program can continue running
CTo make the code shorter without any error handling
DTo speed up the program execution
Attempts:
2 left
💡 Hint
Think about what happens if an error is not handled in a program.
🔧 Debug
advanced
2: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")
AErrno::ENOENT
BSyntaxError
CFileNotFoundError
DNoMethodError
Attempts:
2 left
💡 Hint
Check Ruby's error class for missing files.
Predict Output
advanced
2: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
ARuntimeError
BOops
CHandled inner
DUnhandled exception
Attempts:
2 left
💡 Hint
Look at how the inner rescue handles the second raise.
🚀 Application
expert
3: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
A1
B0
C3
D2
Attempts:
2 left
💡 Hint
Check which values of i are even in the loop.