Sub topic 1
What exceptions are and how to read a traceback
Prerequisites
This chapter assumes you can:
- Write and call Python functions.
- Use
if,for, andwhile. - Read basic class syntax, including inheritance.
You do not need to know try yet. The next chapters cover it.
What an exception is
An exception is an object that Python creates when an operation cannot continue. Dividing by zero, converting "abc" with int(), and reading a missing dictionary key each create one. The exception has a type, such as ZeroDivisionError, and a message that explains what went wrong.
When Python raises an exception, it stops running the current line. It then looks for code that handles the exception. If none exists in the current function, Python leaves that function and checks the function that called it. This is called propagation. If the exception reaches the top of the program unhandled, Python prints a traceback and exits.
A failing program
Save this as ratios.py:
def read_ratio(a, b):
return a / b
def report(values):
total = 0
for a, b in values:
total += read_ratio(a, b)
return total
print(report([(4, 2), (1, 0)]))The first pair works. The second pair divides by zero. Running the file prints this:
Traceback (most recent call last):
File "ratios.py", line 10, in <module>
print(report([(4, 2), (1, 0)]))
File "ratios.py", line 7, in report
total += read_ratio(a, b)
File "ratios.py", line 2, in read_ratio
return a / b
ZeroDivisionError: division by zeroPython 3.11 and later may also print lines of ~ and ^ characters under each source line. They point at the part of the line that failed.
Reading the traceback
Read it from the bottom up.
- The last line gives the exception type and message:
ZeroDivisionError: division by zero. Start here to learn what failed. - The frame just above it shows where the exception was raised: line 2 of
read_ratio, the codereturn a / b. This is usually where you look for the cause. - The frames higher up show how the program got there. Each frame is one function call, listed from the oldest at the top to the newest at the bottom. That is why the header says "most recent call last".
Each frame has a file name, a line number, a function name, and the source line. The name <module> means code at the top level of a file, outside any function.
The failing line is not always the buggy line. Here a / b is correct arithmetic. The real problem is that report passed in a zero. Use the upper frames to find which caller supplied the bad value.
Exceptions are objects with types
Every exception type is a class. ZeroDivisionError is a subclass of ArithmeticError, which is a subclass of Exception. You can check this yourself:
print(ZeroDivisionError.__mro__)This prints the chain of parent classes, from ZeroDivisionError up to object. The next chapters use this hierarchy to decide which handler catches which error.
Exercise
A traceback has three frames: <module> at line 12, load at line 8, and parse at line 3. The last line is ValueError: invalid literal for int() with base 10: 'x'. Which function raised the exception, and which frame is the entry point of the call chain?
Show answer
The exception was raised in parse at line 3, the bottom frame, which is the most recent call. The entry point is the <module> frame at the top, which is where the program started the chain: <module> called load, and load called parse.