python1def share(total, people):2 return total / people3try:4 each = share(12, 0)5except ZeroDivisionError as err:6 print("Oops:", err)7print("Done")<module>each: not setshare()total=12 people=0Tracebackshare(12, 0)Oops: division by zeroDoneZeroDivisionError
Code card: share.py; the highlighted line is the one runningPython interpreter: runs the code and prints tracebacksTerminal: where print() and tracebacks appearCall stack: one frame per running call, newest on topAn exception is an object Python raises when a line cannot finish. In share.py, line 4 calls share(12, 0), which gets its own frame on the call stack; line 2 divides by zero and raises a ZeroDivisionError. The exception climbs out of share(), whose frame is dropped, back to line 4. Because line 4 is inside try, the matching except clause on line 5 catches it, the handler prints, and the program carries on. In the last step try and except are gone: nothing catches the exception, Python prints a traceback and stops before Done.

What can go wrong

  1. Some mistakes only show up while a program runs, such as dividing by zero. Python then raises an exception: an object that names what went wrong. If nothing catches it, the program stops.

Raised and caught

Uncaught

Try it yourself

;; step 1/10
>>> 12 / 0
Traceback (most recent call last):
  ...                    # where it happened
ZeroDivisionError: division by zero

>>> int("ten")         # another kind of exception
Traceback (most recent call last):
  ...
ValueError: invalid literal for int() with base 10: 'ten'

On macOS and Linux the command is often python3 rather than python; on Windows the py launcher also works. The $ is the terminal's own prompt: you do not type it. The figure shortens the traceback. The real one lists each call, oldest first and newest last, with its file, line number and source line, then the exception type and message. In the real message, the ... is the full path to the file.