Index Ai Academy
Phase 0 · ToolsPython core

Errors and exceptions

About 25 minLooking ahead: some prerequisites aren't done yet

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:

  1. The last line names the exception type and gives a message: ZeroDivisionError: division by zero.
  2. The line above it shows where it happened: line 2, inside conversion_rate.
  3. The lines above that show how the program got there: line 9 called report, which called conversion_rate on 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:

ExceptionUsually meansExample
NameErrorA name is misspelled or wasn't created yetprint(totl)
TypeErrorThe operation doesn't work on that type"5" + 5
ValueErrorThe type is right but the value isn't usableint("five")
IndexErrorA list position doesn't exist[1, 2][5]
KeyErrorA dictionary has no such key{"a": 1}["b"]
ZeroDivisionErrorDividing by zero10 / 0
AttributeErrorThat value has no such method or attribute(42).upper()
SyntaxErrorPython can't even read the codea 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])