Bird
0
0

Consider this Ruby code:

hard📝 Application Q9 of 15
Ruby - Error Handling
Consider this Ruby code:
def safe_divide(a, b)
  begin
    result = a / b
  rescue ZeroDivisionError
    result = nil
  end
  result
end

puts safe_divide(10, 0)
puts safe_divide(10, 2)
What is the output?
A10 5
Bnil 5
CError 5
D0 5
Step-by-Step Solution
Solution:
  1. Step 1: Analyze safe_divide with zero divisor

    Dividing by zero raises ZeroDivisionError, caught by rescue, sets result to nil.
  2. Step 2: Analyze safe_divide with divisor 2

    Division succeeds, result is 5.
  3. Final Answer:

    nil 5 -> Option B
  4. Quick Check:

    Rescue returns nil on error = D [OK]
Quick Trick: Rescue can assign fallback values on error [OK]
Common Mistakes:
  • Expecting error instead of nil
  • Confusing zero with nil
  • Ignoring rescue effect

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes