Python
Topic 12 · Writing real programs · ⏱ about 3 h

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.

Show:
In this topic
Beginner

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.

Traceback (most recent call last): File "clean.py", line 12, in <module> rate = no_shows / total ZeroDivisionError: division by zero

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:

def parse_age(text): age = int(text) # may raise ValueError if not 0 <= age <= 120: raise ValueError(f"impossible age: {age}") return age try: age = parse_age("212") except ValueError as e: print("skipping bad row:", e)

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.

Try 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.

Try it

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.

Beginner

Handling exceptions: try, except, else, finally

def safe_ratio(a, b): try: r = a / b except ZeroDivisionError: # only the error you expect return None else: # runs only if no error happened return round(r, 3) finally: # always runs: tidy up here print("ratio checked")
  • Catch specific exceptions. A bare except: also swallows typos and Ctrl+C, hiding real bugs.
  • Keep the try block 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.
Beginner

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:

def bmi(weight_kg, height_m): if height_m <= 0: raise ValueError(f"height_m must be positive, got {height_m}") return weight_kg / height_m ** 2

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).

Beginner

Debugging methods that work

  1. Read the last line of the traceback first, then the line it points to in your code.
  2. Reproduce it with the smallest input that still fails.
  3. Look at the values: print(repr(x), type(x)), or pause the program with breakpoint() and inspect variables in the debugger (type n for next line, p x to print, c to continue). Editors such as VS Code let you click to set breakpoints.
  4. Check your assumptions with assert: assert len(X) == len(y), "X and y differ in length" stops immediately if something you believed is false.
  5. For programs that run for a long time, use the logging module instead of print: messages get timestamps and levels (DEBUG, INFO, WARNING, ERROR) that you can switch on and off.
Beginner

Code: handling and raising errors

Parse messy input, skip bad rows with a reason, and validate arguments.

Python
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)
Open in playground β†—
Beginner

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.

Exercise 1. Safe division

Write safe_divide(a, b) that returns a / b, or None if b is zero, using try and except ZeroDivisionError.

Exercise 2. Parse numbers, skip bad ones

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.

Exercise 3. Validate with raise

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.

Beginner

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.
Check yourself

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…

Go deeper

πŸ“š 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.

Ready