All coding lessonsLesson 9 of 10

Errors, Exceptions and Debugging

Reading tracebacks and writing code that fails gracefully

There are two kinds of problems: syntax errors, where Python cannot even parse your file, and exceptions, which happen while the program runs.

Common exceptions

  • TypeError — an operation on the wrong type, e.g. "3" + 3
  • ValueError — right type, impossible value, e.g. int("abc")
  • NameError — using a variable that was never assigned
  • IndexError — list index out of range
  • KeyError — dictionary key not present
  • ZeroDivisionError — dividing by zero
  • AttributeError — the object has no such method

Reading a traceback

Read a traceback from the bottom up. The last line names the exception type and message; the lines above show the call chain and the exact line number where it happened. That is almost always enough to find the bug.

Handling exceptions

try:
    value = int(input("A number: "))
    result = 100 / value
except ValueError:
    print("That was not a number")
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("Result:", result)   # runs if no exception
finally:
    print("Done")              # always runs

Catch specific exceptions. A bare except: swallows every problem, including typos in your own code, and turns a loud bug into a silent one.

Raising your own

def withdraw(balance, amount):
    if amount > balance:
        raise ValueError("insufficient funds")
    return balance - amount

Debugging strategy

  • Reproduce the bug reliably before changing anything.
  • Print the values of the variables just before the failing line.
  • Cut the problem in half: does the first part still work on its own?
  • Use assert to state assumptions: assert len(data) > 0
  • Change one thing at a time and re-run.
Ask Teacher Smith questions about this Python lessonOpens your AI tutor with a question about “Errors, Exceptions and Debugging” →