Sub topic 1
What exceptions are and how to read a traceback
An exception is Python's way of reporting that something stopped a piece of code from doing what it was asked to do. This chapter covers how exceptions travel up the call stack and how to read the traceback Python prints when one is not handled. The try statement itself comes in the next chapter.
Prerequisites
This chapter assumes you can:
- Write and call Python functions, including functions that call other functions.
- Use
if,for, andwhile. - Run a script from a terminal and see its output.
- Read basic class syntax, since exceptions are objects with classes.
You do not need to have written any error handling yet.
Exceptions are objects that interrupt normal flow
When Python hits a problem it cannot continue past, it creates an exception object and raises it. Normal execution stops at that point. Examples include converting "two" with int(), dividing by zero, or reading a missing dictionary key.
Each exception has:
- A type, such as
ValueErrororKeyError. The type says what category of problem occurred. - Arguments, usually a message, stored in
args. - A traceback, which records where it happened and how execution got there.
Exceptions are not return values. A function that raises does not return anything. Its caller never receives a result, and the exception moves on instead.
| Exception | Typical cause |
|---|---|
| `ValueError` | Right type, unacceptable value: `int("two")` |
| `TypeError` | Wrong type for an operation: `"a" + 1` |
| `KeyError` | Missing dictionary key: `{}["x"]` |
| `IndexError` | Sequence index out of range: `[][0]` |
| `AttributeError` | Missing attribute: `None.strip()` |
| `ZeroDivisionError` | Division or modulo by zero: `1 / 0` |
| `FileNotFoundError` | Opening a path that does not exist |
SyntaxError is different. Python raises it while compiling your file, before any of your code runs, so it never appears as part of a running call stack.
How an exception propagates
Python tracks active function calls in the call stack. Each function call adds a frame to the stack. The frame holds that call's local variables and the line currently executing.
When an exception is raised, Python looks for a handler in the current frame. If there is none, it discards that frame and looks in the caller's frame. This repeats up the stack and is called unwinding. If the exception reaches the top of the stack without being handled, the interpreter prints the traceback and the program exits with a non-zero status.
Two consequences follow:
- Code after the failing line in each unwound frame never runs, unless a
finallyblock or context manager covers it. Those are covered in later chapters. - An exception can be handled at any level. A low-level function can raise, and a function far up the stack can decide what to do.
Reading a traceback
Save this as config.py:
def parse_line(line):
name, value = line.split("=")
return name, int(value)
def parse_all(lines):
result = []
for line in lines:
result.append(parse_line(line))
return result
def main():
config = parse_all(["a=1", "b=two"])
print(config)
main()Running python config.py prints:
Traceback (most recent call last):
File "config.py", line 15, in <module>
main()
File "config.py", line 12, in main
config = parse_all(["a=1", "b=two"])
File "config.py", line 8, in parse_all
result.append(parse_line(line))
File "config.py", line 3, in parse_line
return name, int(value)
ValueError: invalid literal for int() with base 10: 'two'Read it in this order:
- Start at the last line. It gives the exception type (
ValueError) and the message. The message names the bad value,'two'. - Look at the entry just above it. The last frame is where the exception was raised: line 3 of
parse_line. This is usually the first place to look. - Read upward. Each earlier entry is a caller, ending at the top, so you can see how execution reached the failure. Line 8 shows that
parse_allpassed in the line"b=two". - Use the source line shown under each entry. Python prints the code from the file, so you can often tell what happened without opening the editor.
The header "most recent call last" means the order is oldest call first. Beginners often read from the top, which shows where the program started, not where it failed.
In Python 3.11 and later, tracebacks may also print lines of ^^^^ markers under the source line. They point at the exact part of the expression that failed, which helps when one line contains several operations, for example a["x"]["y"].
Where the cause lies
The raising line is not always the line to fix. Here, int(value) failed, but the real problem is the input "b=two". The question to ask is which function received a value it could not accept, and whether that function or its caller should have prevented it. The frames above the failing line show you what called it and with what arguments.
Tracebacks from chained exceptions
Sometimes a traceback contains more than one block. This happens when an exception is raised while another is being handled, or when code raises one exception deliberately in response to another. Python then prints both, separated by a sentence:
The above exception was the direct cause of the following exception:means the code explicitly linked the two withraise ... from ....During handling of the above exception, another exception occurred:means a new exception was raised inside anexceptblock, often by accident.
In both cases, read the first block as the original problem and the last block as the exception that finally escaped. Chaining is covered in its own chapter, so for now just recognize the format.
Inspecting an exception programmatically
The traceback printed on exit is built from data stored on the exception. You can read that data yourself when you catch an exception. The as exc form used here is covered properly later in the tutorial.
import traceback
def divide(a, b):
return a / b
try:
divide(1, 0)
except ZeroDivisionError as exc:
print(type(exc).__name__, exc.args)
tb = exc.__traceback__
print(tb.tb_frame.f_code.co_name, tb.tb_lineno)
traceback.print_exc()The first print shows ZeroDivisionError ('division by zero',). The second shows <module> 7. exc.__traceback__ points to the outermost frame the exception passed through, which here is the module-level code that called divide on line 7. traceback.print_exc() prints the full traceback to standard error, in the same format as an uncaught exception, but the program keeps running.
Useful tools from the traceback module:
traceback.print_exc()prints the current exception's traceback to standard error.traceback.format_exc()returns the same text as a string, for example for logging.
Common mistakes when reading tracebacks
- Reading only the top. The top shows the program entry point, not the failure.
- Ignoring the message. Text such as
'two'orlist index out of rangeoften identifies the bad value directly. - Blaming library code. If the last frames are inside a library, scan upward for the lowest frame in your own files. That is usually the call that passed bad input.
- Stopping at the last line. Where the exception was raised can differ from where the wrong value was created, so follow the arguments up the stack.
Summary of the model
- An exception is an object with a type, arguments, and a traceback.
- Raising it stops the current function and unwinds frames until a handler is found.
- If none is found, Python prints the traceback and exits with a non-zero status.
- To read a traceback, start from the last line, then work upward through the callers.
Exercise
This traceback is printed when a script runs. Which function raised the exception, which line of the file held the failing code, and which function called it? Traceback (most recent call last): File "report.py", line 20, in <module> run() File "report.py", line 15, in run total = addprices(items) File "report.py", line 7, in addprices return sum(item["price"] for item in items) KeyError: 'price'
Show answer
The exception was raised in addprices, at line 7 of report.py, where item["price"] is looked up. It was called by run on line 15, and run was called from module level on line 20. The error is a KeyError for the key 'price', so at least one item in items has no "price" key. To find the cause, check what run passed into addprices.
Exercise
Why does the line print(config) in main() from config.py never execute when the program is run, and what status does the interpreter exit with?
Show answer
The ValueError raised in parseline is not handled in parseline, parseall, or main. Python unwinds each frame, so execution never reaches the print call, which comes after parseall in main. The exception reaches the top level, the interpreter prints the traceback, and the process exits with a non-zero status (1 for an uncaught exception).