Python Fundamentals ยท Objects, Errors and Generators

Exceptions: try, except, finally and raise

Catch errors so the program keeps going, run clean-up code no matter what, and raise your own errors for bad input.

exceptions.py

def safe_divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        result = None           # handled: the program keeps going
    finally:
        print("checked", a, "/", b)   # runs whether or not there was an error
    return result

def parse_age(text):
    age = int(text)
    if age < 0:
        raise ValueError("age cannot be negative")
    return age

x = safe_divide(10, 2)
y = safe_divide(1, 0)
try:
    parse_age("-3")
except ValueError as error:
    message = str(error)
print(x, y, message)

Step by step

  1. Python defines the function safe_divide(). Its body does not run yet: it runs each time the function is called.
  2. Python defines the function parse_age(). Its body does not run yet: it runs each time the function is called.
  3. safe_divide(10, 2): no problem expected.
  4. Line runs: try:.
  5. 10 / 2 = 5.0 without an error, so the except block is skipped.
  6. finally runs anyway.
  7. The function returns result.
  8. safe_divide(10, 2): no problem expected.
  9. Now 1 / 0.
  10. Line runs: try:.
  11. Dividing by zero raises ZeroDivisionError. Python jumps straight to the matching except.
  12. Line runs: except ZeroDivisionError:.
  13. Handled: result is None, and the program carries on.
  14. finally runs again, error or not.
  15. The function returns result.
  16. Now 1 / 0.
  17. Line runs: try:.
  18. Python calls parse_age(), with text = '-3'. It gets its own names.
  19. age is created with the value -3.
  20. Python checks age < 0 to decide which way the code goes.
  21. age is negative: raise our own ValueError with a message.
  22. parse_age() has finished, so its names are gone.
  23. The error travels up to the caller's except, which catches it and names it error.
  24. message is created with the value 'age cannot be negative'. error goes out of scope and disappears.
  25. x = 5.0, y = None, and the message from our own error. Errors were caught, handled, and the program finished normally.