1.Why should I care?
Error messages are not insults; they are the most useful debugging information you will ever get for free. Engineers who read them calmly fix crashes in seconds instead of hours.
- ◇ Read a traceback from the bottom up to find the error type, message and line.
- ◇ Tell syntax errors, runtime errors and logic errors apart.
- ◇ Name the usual cause of NameError, TypeError, ValueError, ZeroDivisionError and IndexError.
2.Discover
Work through 'Text plus a number', 'Mean of an empty log' and 'One equals sign'. For each, read the traceback from the bottom, pick the line you suspect and check. Use the print probe to see the variables just before the crash.
Loading the interactive…
Can't use the interactive? Read a description instead
The bug hunt shows a short program, what was expected and what actually happened. 'Text plus a number' crashes on line 3 with TypeError: can only concatenate str (not "float") to str. 'Mean of an empty log' crashes on line 5 inside mean, called from line 7, with ZeroDivisionError. 'One equals sign' fails before running with a SyntaxError on line 3, suggesting '=='. Selecting a line and checking explains the cause and the fix.
3.Checkpoint: guided practice
Check what you just discovered before going on. Hints appear after a wrong answer.
Practice 1
Which part of a traceback tells you the kind of error?
Practice 2
Which is a logic error?
4.Predict
A traceback ends with ZeroDivisionError: division by zero, and the line above says line 5, in mean. Where is the fault?
Guess first. Being wrong here is how the surprise works.
5.Understand
Bottom up
Traceback (most recent call last):
File "log.py", line 7, in <module>
print(mean([]))
File "log.py", line 5, in mean
return total / len(readings)
ZeroDivisionError: division by zeroLast line: the error type and message. Just above: the file, line and code where it happened. Higher up: the chain of calls that got there (line 7 called mean).
Three kinds of error
Syntax errors stop the program before anything runs: if x = 5: (Python even suggests ==). Runtime errors crash it part-way: dividing by zero, adding text to a number. Logic errors never crash: the program runs and gives a wrong answer. Logic errors are the hardest, so tests matter.
The usual suspects
NameError: a misspelt name or one used before it is assigned. TypeError: the wrong type, such as "23.5" + 0.4. ValueError: right type, bad value, such as float("ERR"). ZeroDivisionError: dividing by zero, often an empty list. IndexError: a list position that does not exist, such as readings[7] in a 7-item list.
Explain it another way
A traceback is a trail of footprints. The crash is at the end of the trail; earlier footprints show how you got there.
When an exception is not handled, Python unwinds the call stack and prints each frame, oldest first, then the exception type and message. Python 3.11 and later also underline the exact part of the line that failed.
On robots and servers, tracebacks are written to log files. The first thing an engineer does after a failure is find the last traceback in the log and read it from the bottom.
Worked example 1
A traceback ends: IndexError: list index out of range, at line 4: last = readings[len(readings)]. Explain and fix.
A list of n items has positions 0 to n − 1, so readings[len(readings)] is one past the end. Use readings[len(readings) - 1] or simply readings[-1].
Common mix-ups
- The first line of a traceback is the most important.
✓ The last line names the error, and the line above it shows where. Read from the bottom. - No error message means no bug.
✓ Logic errors give wrong answers silently. Only tests and checks reveal them.
6.Practice on your own
Practice, not a test. Wrong answers get a hint and another try.
Practice 3
float("ERR") raises which error?
Practice 4
A list has 7 readings. What is the largest valid index?
7.Apply it
Write five tiny programs, each causing one of NameError, TypeError, ValueError, ZeroDivisionError and IndexError. Run each and copy its last traceback line into a table with one sentence on the cause and the fix.
8.Reflect
9.Go further
- Python tutorial: errors and exceptions ↗Official explanations of syntax errors, exceptions and tracebacks.
Concepts: Testing and debugging