Python Exception Types and Tracebacks
What you will learn
- How to read a traceback and find the line to fix
- The common built-in exceptions and what causes each
- The family tree of exceptions
- Syntax errors versus exceptions
- Printing a traceback yourself with the
tracebackmodule
1. Reading a traceback
When an error is not caught, Python prints a traceback: the trail of function calls that led to the error. Here is a small program saved as shop.py:
def average(values):
return sum(values) / len(values)
def report(groups):
for g in groups:
print(average(g))
report([[1, 2, 3], []])
Running it prints:
2.0
Traceback (most recent call last):
File "shop.py", line 8, in <module>
report([[1, 2, 3], []])
~~~~~~^^^^^^^^^^^^^^^^^
File "shop.py", line 6, in report
print(average(g))
~~~~~~~^^^
File "shop.py", line 2, in average
return sum(values) / len(values)
~~~~~~~~~~~~^~~~~~~~~~~~~
ZeroDivisionError: division by zero
(The real output shows the full file path in each File line; it is shortened here.) The first group printed 2.0; the second, an empty list, caused the error.
Read it from the bottom up:
- The last line says what went wrong: the exception type and message (
ZeroDivisionError: division by zero). - The line above it shows where it happened: file
shop.py, line 2, inaverage, with the codereturn sum(values) / len(values). The~and^marks point at the part that failed. - Going upward shows who called whom:
averagewas called fromreport(line 6), which was called from the main program (<module>, line 8).
Start at the bottom, find the line, and ask why the value was bad. Here: len(values) was 0 because the list was empty. The fix could be a check for an empty list, or a try and except in the right place (lesson 14.1).
Quick check: in a traceback, which line tells you the type of error?
The last line.
2. Common exceptions
These are the errors you will meet most. Each example below was run with Python 3.13, and the message is what Python printed.
Wrong value or wrong type
| Exception | Meaning | Example and message |
|---|---|---|
ValueError |
right type, unsuitable value | int('x'): invalid literal for int() with base 10: 'x' |
TypeError |
operation on the wrong type | 'a' + 1: can only concatenate str (not "int") to str |
len(5): object of type 'int' has no len() |
||
iter(5): 'int' object is not iterable |
||
| wrong number of arguments | (lambda a: a)(1, 2): ... takes 1 positional argument but 2 were given |
|
| immutable object | t[0] = 1 for a tuple: 'tuple' object does not support item assignment |
Other ValueErrors: float('a') (could not convert string to float: 'a'), [1, 2].index(9) (9 is not in list), and unpacking the wrong number of items: a, b = [1, 2, 3] gives too many values to unpack (expected 2).
Missing item
| Exception | Meaning | Example and message |
|---|---|---|
IndexError |
list/tuple position out of range | [1][3]: list index out of range |
[].pop(): pop from empty list |
||
KeyError |
key not in the dictionary (or set remove) |
{}['k']: 'k' |
AttributeError |
the object has no such attribute or method | None.x: 'NoneType' object has no attribute 'x' |
'abc'.foo(): 'str' object has no attribute 'foo' |
AttributeError: 'NoneType' ... is very common: a function that was supposed to return an object returned None instead (lesson 11.2).
Names and scope
| Exception | Meaning | Example |
|---|---|---|
NameError |
a name that does not exist (often a typo) | print(undefined): name 'undefined' is not defined |
UnboundLocalError |
a local name read before it is assigned | cannot access local variable 'y' where it is not associated with a value |
Files and imports
| Exception | Example and message |
|---|---|
FileNotFoundError |
open('nope.txt'): [Errno 2] No such file or directory: 'nope.txt' |
ModuleNotFoundError |
import nomod: No module named 'nomod' |
Maths and limits
| Exception | Example and message |
|---|---|
ZeroDivisionError |
1 / 0: division by zero |
OverflowError |
2.0 ** 10000: (34, 'Result too large') |
RecursionError |
a function calling itself forever: maximum recursion depth exceeded (lesson 11.6) |
StopIteration |
next(iter([])): raised when an iterator has no more items (lesson 12.4) |
3. The family tree
All exceptions are classes, arranged in a tree. Catching a parent catches all its children:
print(FileNotFoundError.__mro__)
print(KeyError.__mro__)
(<class 'FileNotFoundError'>, <class 'OSError'>, <class 'Exception'>, <class 'BaseException'>, <class 'object'>)
(<class 'KeyError'>, <class 'LookupError'>, <class 'Exception'>, <class 'BaseException'>, <class 'object'>)
A simplified view of the tree:
BaseException
├── KeyboardInterrupt, SystemExit (not caught by "except Exception")
└── Exception
├── ArithmeticError (ZeroDivisionError, OverflowError)
├── LookupError (IndexError, KeyError)
├── OSError (FileNotFoundError, PermissionError, ...)
├── ValueError (UnicodeError is a kind of ValueError)
├── TypeError
├── AttributeError
├── NameError (UnboundLocalError)
├── ImportError (ModuleNotFoundError)
├── RuntimeError (RecursionError)
└── StopIteration
except OSErrorcatchesFileNotFoundError,PermissionErrorand more.except LookupErrorcatches bothIndexErrorandKeyError.except Exceptioncatches nearly everything ordinary, but notKeyboardInterruptandSystemExit.
Use help(OSError) or the Python documentation's "Built-in Exceptions" page for the full tree.
4. Syntax errors are different
A SyntaxError means Python cannot even read the code, so nothing in the file runs. It is reported before the program starts, so you cannot catch it with try in the same file:
print("hello"
SyntaxError: '(' was never closed
Typical causes: a missing colon, a missing closing bracket or quote, wrong indentation (IndentationError is a kind of SyntaxError). Fix these by reading the line the error points to, and the line before it.
An exception, on the other hand, happens while the program runs, on valid code that meets a bad situation.
5. Printing the traceback yourself
When you catch an error, you often want to log the full details without crashing. The traceback module does this:
import traceback
def a():
return 1 / 0
try:
a()
except ZeroDivisionError:
text = traceback.format_exc()
print(text.splitlines()[0])
print(text.splitlines()[-1])
print(len(text.splitlines()))
Traceback (most recent call last):
ZeroDivisionError: division by zero
8
traceback.format_exc()returns the full traceback as text (eight lines here); you can write it to a log file.traceback.print_exc()prints it.
In bigger programs the logging module's logger.exception(...) does the same job (lesson 17.9).
6. A debugging routine
When a traceback appears:
- Read the last line. What type and message?
- Find the lowest
Fileline that is in your code. (Lines inside Python's libraries are usually correct; the bug is in the call that led there.) - Look at the values on that line. Add a
printjust before it if needed (lesson 18.1 has a better tool). - Ask: was the input bad, or the code?
- Fix the cause (not just hide the error with
try).
Worked example: from traceback to fix
A function averages marks per class. Run on a list containing an empty class, it crashes. We read the error, then fix it two ways.
def average(values):
return sum(values) / len(values)
classes = {"A": [70, 80, 90], "B": [], "C": [60, 65]}
try:
for name, marks in classes.items():
print(name, average(marks))
except ZeroDivisionError as e:
print("Stopped:", e)
def safe_average(values):
"""Return the average, or None if there are no values."""
if not values:
return None
return sum(values) / len(values)
for name, marks in classes.items():
avg = safe_average(marks)
print(name, "no marks yet" if avg is None else round(avg, 1))
A 80.0
Stopped: division by zero
A 80.0
B no marks yet
C 62.5
| Step | Lesson |
|---|---|
the type ZeroDivisionError and the line sum(values) / len(values) |
the bottom of the traceback names what and where |
len(values) is 0 for class B |
look at the values |
| the first loop stops at B and never reaches C | catching outside the loop ends the whole loop |
safe_average handles the empty case |
fix the cause with a check, where failure is a normal case |
The class names and marks are made up.
Common mistakes
- Reading a traceback from the top instead of the bottom.
- Ignoring the message (
'NoneType' object has no attribute ...tells you a value isNone). - Hiding errors with
tryinstead of fixing the cause. - Trying to catch a
SyntaxErrorin the same file. - Confusing
KeyErrorwithIndexError(keys versus positions). - Looking only at the last line, and not the line in your own code that led to it.
Key takeaways
- A traceback lists the calls that led to the error: read from the bottom (what happened), then up (where and who called).
- Learn the common ones:
ValueError,TypeError,KeyError,IndexError,AttributeError,NameError,FileNotFoundError,ZeroDivisionError. - Exceptions form a tree; catching a parent such as
OSErrororLookupErrorcatches its children. - A
SyntaxErrorstops the program before it starts and cannot be caught in the same file. traceback.format_exc()gives the traceback as text for logging.
Practice
1. Which part of a traceback names the type of error?
Show answer
The last line, for example KeyError: 'k'.
2. What is the difference between IndexError and KeyError?
Show answer
IndexError is a position out of range in a list, tuple or string. KeyError is a key missing in a dictionary.
3. What does AttributeError: 'NoneType' object has no attribute 'append' usually mean?
Show answer
The variable holds None (often because a function returned nothing, or you wrote x = x.sort()), and you tried to call a method on it.
4. Which exception family does except OSError catch from this list: FileNotFoundError, KeyError, PermissionError?
Show answer
FileNotFoundError and PermissionError. KeyError is a LookupError.
5. Why can't you catch a SyntaxError with try in the same file?
Show answer
Python reads the whole file first; the error happens before any of it runs, so the try never starts.
6. How do you get a traceback as text inside an except block?
Show answer
traceback.format_exc() (or traceback.print_exc() to print it).