Exceptions & recovery

Handle the unexpected

Lesson 10 of 20 · 9 min · Module 4: Reliable little programs

An exception reports an operation that could not finish. Catch a specific expected error when your program has a sensible recovery path.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Understand an exception as a failure signal
  • Catch a specific exception type
  • Define a meaningful fallback value

The idea

Put the operation inside try. Use except ZeroDivisionError to handle division by zero. Return None when no numeric answer is available.

try:
    value = 10 / 0
except ZeroDivisionError:
    value = None
print(value) # None

01Keep the protected operation small

Wrap the operation you expect might fail, not a whole unrelated program. That makes it easier to know what an except block is recovering from.

02Keep zero distinct from no result

A real calculation can return zero. None represents the absence of a result, so callers can distinguish those cases with value is None.

Your turn

Define safe_divide(a, b) for numeric inputs. Return a divided by b, or None when b is zero. Other unexpected errors should not be silently swallowed.

What the checks look for

  • Divides ordinary numbers
  • Returns None for division by zero
  • Preserves fractional and negative results
Try it in the editor →

Take this with you

Recover deliberately from expected errors; let unexpected problems remain visible.

Learn Python Foundations for free

20 short lessons with real code and instant checks.

See the whole course →