Quick Answer
Handling mathematical division safely
Understanding the Issue
This error occurs when attempting to divide by zero. Always validate denominators before division operations.
The Problem
This code demonstrates the issue:
Ruby
Error
# Problem: Unsafe division
def calculate(x, y)
x / y
end
calculate(5, 0) # ZeroDivisionError
The Solution
Here's the corrected code:
Ruby
Fixed
# Solution 1: Check zero
def calculate(x, y)
return Float::INFINITY if y.zero?
x.to_f / y
end
# Solution 2: Rescue
begin
1 / 0
rescue ZeroDivisionError
"Cannot divide by zero"
end
Key Takeaways
Validate denominators before division.