Errors, Exceptions & Debugging
Read tracebacks calmly, handle errors with try and except, raise your own errors to validate input, and debug with print, logging, assert and the debugger.
Errors, debugging and reading tracebacks
When something goes wrong, Python stops and prints a traceback. Read it from the bottom up: the last line names the error type and message, and the lines above show where it happened.
The common ones: NameError (a misspelt or undefined variable), TypeError (wrong type, like adding text to a number), KeyError (a dictionary key that doesn't exist), IndexError (a position past the end of a list), ValueError (right type, bad value, like int("abc")), IndentationError and SyntaxError (the code isn't valid Python).
You can handle errors you expect, so one bad record doesn't stop a whole job, and raise your own when input is invalid:
A debugging routine that works: read the last line of the traceback; print the values just before the failing line; shrink the input until the problem is tiny; change one thing at a time. Searching the exact error message, or asking an AI assistant to explain it, is fine; make sure you understand the fix before using it.
Code example: parsing text and handling errors
A worked example: read it step by step (every part is explained), then run it and experiment.
Interactive: this part runs in your browser.
Read a traceback, step by step
A traceback is Python telling you exactly where things went wrong. Step through one, part by part.
Interactive: this part runs in your browser.
Handling exceptions: try, except, else, finally
- Catch specific exceptions. A bare
except:also swallows typos and Ctrl+C, hiding real bugs. - Keep the
tryblock small, so you know which line you are protecting. - Only catch an error if you can do something sensible about it (use a default, skip a bad row, ask again). Otherwise let it stop the program with a clear message.
Raising errors to protect your code
Check inputs at the start of a function and raise a clear error when they are wrong. Failing early, with a message that says what was expected, saves hours of debugging later:
Common built-in exceptions: ValueError (right type, bad value), TypeError (wrong type), KeyError (missing dictionary key), IndexError (position past the end), FileNotFoundError, and AttributeError (the object has no such method or attribute, often a typo or a None where you expected an object).
Debugging methods that work
- Read the last line of the traceback first, then the line it points to in your code.
- Reproduce it with the smallest input that still fails.
- Look at the values:
print(repr(x), type(x)), or pause the program withbreakpoint()and inspect variables in the debugger (typenfor next line,p xto print,cto continue). Editors such as VS Code let you click to set breakpoints. - Check your assumptions with
assert:assert len(X) == len(y), "X and y differ in length"stops immediately if something you believed is false. - For programs that run for a long time, use the
loggingmodule instead of print: messages get timestamps and levels (DEBUG, INFO, WARNING, ERROR) that you can switch on and off.
Code: handling and raising errors
Parse messy input, skip bad rows with a reason, and validate arguments.
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s", force=True)
raw = ["72.5", "68", "n/a", "", "81.2", "-5"]
def parse_weight(text):
value = float(text) # may raise ValueError
if value <= 0:
raise ValueError(f"weight must be positive, got {value}")
return value
weights = []
for row, text in enumerate(raw):
try:
weights.append(parse_weight(text))
except ValueError as err:
logging.warning("row %d skipped: %s", row, err)
print("clean weights:", weights)
assert all(w > 0 for w in weights), "a non-positive weight slipped through"
d = {"age": 34}
try:
print(d["height"])
except KeyError as err:
print("missing key:", err)Practice: check yourself
Write the code, then press β Check my answer: hidden tests run your code and tell you exactly what is right. βΆ Run just shows the output. Stuck? Use a hint; the solution is there if you need it.
Write safe_divide(a, b) that returns a / b, or None if b is zero, using try and except ZeroDivisionError.
raw = ["12", "7.5", "abc", "", "3"]. Build numbers with the values that can be converted with float() (skipping the rest), and bad with the ones that cannot.
Write set_age(age) that returns age if it is a whole number from 0 to 130, and otherwise raises ValueError with a helpful message.
Summary
Key words
- exception
- an error that happens while the program runs
- traceback
- Python's report of where an error happened, read from the bottom up
- try / except
- run code and handle a specific error if it happens
- raise
- signal an error yourself, to reject bad input
- debugging
- finding and fixing the cause of a problem
Common mistakes
- A bare
except:that hides every error, including your own typos. Catch the specific error. - Reading only the top of a traceback: the real cause is at the bottom.
- Using try/except to hide a bug instead of fixing it.
Quiz
1. The last line of a traceback says KeyError: 'age'. What happened?
2. Which part of a traceback should you read first?
3. Why avoid a bare except:?
4. When does an else block after try/except run?
5. AttributeError: 'NoneType' object has no attribute 'append' most likely meansβ¦
π Further reading
Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.
- The Python Tutorial: Errors and Exceptions β try, except, raise and clean-up actions
- pdb: the Python debugger β breakpoint() and debugger commands