Errors and exceptions
Why this matters
Code that talks to the outside world fails in ordinary ways all the time. A file is missing, an API times out, a model returns text that isn't valid JSON. How your code handles those failures is what separates a fragile script from a reliable tool. Reading a traceback quickly is also the fastest debugging skill there is, whether you wrote the code or an AI assistant did.
- Read a traceback from the bottom up and find the line that failed
- Recognize the common exception types and what usually causes each
- Handle an expected failure with try and except, plus else and finally
- Raise your own exception when a function gets input it can't use
Reading a traceback
An error that happens while a program runs is called an exception. If nothing handles it, Python stops and prints a traceback. That's a report of what went wrong, and of the chain of calls that led there. Think of a package's tracking history: the last entry tells you where it got stuck, and the ones above show the route it took. Run this and read the result:
def conversion_rate(conversions, clicks): return conversions / clicks def report(name, conversions, clicks): rate = conversion_rate(conversions, clicks) print(name, rate) report("Spring Sale", 301, 5470) report("Holiday Teaser", 0, 0)
Read a traceback from the bottom up:
- The last line names the exception type and gives a message:
ZeroDivisionError: division by zero. - The line above it shows where it happened: line 2, inside
conversion_rate. - The lines above that show how the program got there: line 9 called
report, which calledconversion_rateon line 5.
Notice the first report printed before the crash. Everything before the failing line ran normally. Python stops at the failure.
On your own computer, tracebacks start with Traceback (most recent call last): and include file names, but they read the same way. The academy shortens them to the lines of your code.
The usual suspects
A handful of exception types cover most of the errors you'll meet:
| Exception | Usually means | Example |
|---|---|---|
NameError | A name is misspelled or wasn't created yet | print(totl) |
TypeError | The operation doesn't work on that type | "5" + 5 |
ValueError | The type is right but the value isn't usable | int("five") |
IndexError | A list position doesn't exist | [1, 2][5] |
KeyError | A dictionary has no such key | {"a": 1}["b"] |
ZeroDivisionError | Dividing by zero | 10 / 0 |
AttributeError | That value has no such method or attribute | (42).upper() |
SyntaxError | Python can't even read the code | a missing colon or bracket |
SyntaxError is different from the rest. Python checks the whole file before running anything, so a syntax error means no line runs. Every other exception happens partway through, when the bad line is reached.
budgets = [5000, 2000, 8000] print(budgets[3])