Common exceptions

Each built-in error usually points at one kind of bug. Learn these and most tracebacks explain themselves.

  • KeyError: a dict key isn't there. Use .get() if missing is normal.
  • IndexError: past the end of a list. The last index is len(x) - 1.
  • TypeError: the wrong type, like "total: " + 5, or the wrong number of arguments.
  • AttributeError: 'NoneType' object has no attribute ...: a variable is None. Usually a function forgot to return, or a method like list.sort() that returns None was assigned.
  • ValueError: right type, bad value, like int("12.5").
  • RecursionError: a recursive function never reached its base case. Python stops it at about 1000 calls deep.
  • ZeroDivisionError: often an average of an empty list.

When you see one in an interview, read the last line of the traceback out loud and say what it usually means. The Debugging challenges practise exactly this.

Run it, then add a case of your own.