Part 06 / Topic 2 of 10
Reading a traceback
When an exception is not handled, Python prints a traceback. Read it from the bottom up.
Real-world example: an average-marks function gets an empty list.
def average(marks):
return sum(marks) / len(marks)
print(average([]))
Traceback (most recent call last):
File "report.py", line 4, in <module>
print(average([]))
~~~~~~~^^^^
File "report.py", line 2, in average
return sum(marks) / len(marks)
~~~~~~~~~~~^~~~~~~~~~~~
ZeroDivisionError: division by zero
- Last line: the exception type and message โ
ZeroDivisionError: division by zero. - Line above it: the exact line that failed (line 2, inside
average). - Top lines: how we got there (line 4 called
average).
๐ Going deeper: the
~~~^^^markers (Python 3.11+) point at the exact part of the line that failed. "most recent call last" means the newest call is at the bottom, which is why you read upwards.
Done here? The practice set for Part 6 โ 7 exercises with solutions โ is on the part page.