Debugging and testing · 1 / 14 Theory

Types of errors and how to read a traceback

All programmers make mistakes, every day. The difference between a beginner and a professional is that the professional knows how to read what Python says and looks for the cause with method.

The three types of error

TypeWhen it appearsExample
SyntaxBefore running: Python does not understand the codeA missing : or parenthesis
Runtime (exception)While running: something impossibleDividing by zero, using an index that does not exist
LogicIt never warns: the program works, but gives a wrong resultA > condition that should have been >=

The first two are detected automatically. Logic errors are the hardest: nobody warns you, which is why you need tests.

Syntax errors

# if age >= 18
#     print("adult")
#
# SyntaxError: expected ':'

Python indicates the line and usually points to the problem. Also check the previous line: an unclosed parenthesis there causes the error on the next one.

Exceptions and traceback

When an exception is not caught, Python prints a traceback: the path the program followed until the error.

def divide(a, b):
    return a / b

def calculate(x):
    return divide(x, 0)

print(calculate(10))

# Traceback (most recent call last):
#   File "main.py", line 7, in <module>
#     print(calculate(10))
#   File "main.py", line 5, in calculate
#     return divide(x, 0)
#   File "main.py", line 2, in divide
#     return a / b
# ZeroDivisionError: division by zero

It is read from bottom to top:

  • The last line is the error: the type (ZeroDivisionError) and the message (division by zero).
  • The File line just above indicates where it happened: file, line number and function (divide).
  • The previous lines are the chain of calls that led there: <module> called calculate, and this one called divide.

With this you know what failed and where. To know why, you have to look at which values reached that line. Practice with Read a traceback.

The most common exceptions

ExceptionTypical cause
NameErrorUsing a variable that does not exist (or is misspelled)
TypeErrorOperating with incompatible types: 3 + "a"
ValueErrorValue of the right type, but inappropriate: int("abc")
IndexErrorPosition out of range in a list
KeyErrorKey that does not exist in a dictionary
AttributeErrorAsking for an attribute or method that the object does not have
ZeroDivisionErrorDividing by zero
IndentationErrorIncorrect indentation
data = {"name": "Ana"}

try:
    print(data["age"])
except KeyError as e:
    print("Missing key:", e)   # Missing key: 'age'

Logic errors: the most treacherous

This code gives no error, but it is wrong:

def is_adult(age):
    return age > 18      # it should be >= 18!

print(is_adult(18))   # False  (an 18-year-old would be a "minor")

It is only discovered by testing with the right cases, in this example the value 18. That is what the rest of the lesson is about.