← Practice
πŸ“– Errors and exceptionserrors-safe-divide
LessonΒ·difficulty 2/5Β·~10 min

Errors: safe divide

Errors: safe divide

Some operations can blow up at runtime. Dividing by zero raises an exception:

python
10 / 0     # ZeroDivisionError: division by zero

Instead of letting your program crash, you can catch the error and decide what to do:

python
try:
    risky()
except ValueError:
    print("handled it")

Only the specific exception you name is caught β€” which keeps you from accidentally hiding unrelated bugs.

Your task

Write safe_divide(a, b) that returns a / b, but returns None when b is 0 instead of raising ZeroDivisionError.

python
safe_divide(6, 3)   # 2.0
safe_divide(7, 2)   # 3.5
safe_divide(5, 0)   # None

Hint: wrap the division in try / except ZeroDivisionError.

Tests

  • even division
  • fractional
  • divide by zero
  • negative
  • zero numerator (hidden)

✦ Stuck? Ask for a spark

warming up
Loading editor…

$ Console output will appear here.

>_AI tutor
Sign in to chat with the tutor.