Ruby for Instance / Errors

# Define the safe_division method
def safe_division(numerator, denominator)
  # Attempt to divide the numerator by the denominator
  result = numerator / denominator

  # If a ZeroDivisionError is raised, return 0 instead
  rescue ZeroDivisionError
    0
end

# Try to divide 4 by 2
safe_division(4, 2) # => 2

# Try to divide 4 by 0
safe_division(4, 0) # => 0

Try on playground

Next: methods

made with by dfxe / source / license