Back to Practice
#0069

Safe Divide With Exceptions

EasyPython12 min10 XP

Problem

Return a / b. If b is zero, return None. Do not catch every possible exception.

Why This Matters

Production code should handle expected failures without hiding unrelated bugs.

Function Signature

def safe_divide(a, b):

Examples

Example 1
Inputsafe_divide(10, 2)
Output5.0

Normal division still works.

Example 2
Inputsafe_divide(10, 0)
OutputNone

Division by zero is the expected failure.

Constraints

  • Catch ZeroDivisionError only.
  • Return None for division by zero.
  • Let unrelated type errors surface.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Normal division
Input10, 2
Expected5.0

The function should not always return None.

Zero denominator
Input10, 0
ExpectedNone

Expected error returns fallback.

Hidden Test Categories
negative denominatorfloat divisionunrelated type error should not be swallowed