Skip to content

06. Errors and debugging — Cheat sheet

The essentials of module 06 on one page. Every runnable block on this page is checked against its output.

I want to… Use… Example
find what went wrong the last line of the traceback ValueError: could not convert string to float: 'N/A'
find where it went wrong the last frame from your file File ".../clean_sales.py", line 13, in parse_price
handle one kind of error try / except Type except ValueError:
handle several kinds the same way a tuple except (ValueError, TypeError):
use the error object as err print(type(err).__name__, err)
run code only after a success else: move the next steps out of try
always clean up finally: close a connection, remove a lock file
signal bad input raise raise ValueError(f"quantity must be >= 1, got {q}")
re-raise the current error bare raise in except log, then raise
wrap an error in a clearer one raise New(...) from err raise ConfigError("bad JSON") from err
hide the low-level error raise New(...) from None the new message says it all
add context to an error err.add_note("...") (3.11+) err.add_note("file: data/readings.txt")
define my own error type class Name(BaseError): class MissingColumnError(DataValidationError):
raise several errors at once ExceptionGroup + except* (3.11+) raise ExceptionGroup("validation", errors)
check an invariant of my code assert cond, "message" assert total >= 0, "negative total"
print a name and its value f"{x=}" print(f"{total=}") → total=224.1
pause in the debugger breakpoint() then p total, n, c
debug a crash after it happens python -m pdb -c continue script.py pdb opens at the failing frame
ignore every breakpoint() PYTHONBREAKPOINT=0 PYTHONBREAKPOINT=0 python job.py
log instead of print logging.getLogger(__name__) log.info("loaded %d rows", n)
see INFO / DEBUG messages basicConfig(level=...) logging.basicConfig(level=logging.DEBUG)
log an error with its traceback log.exception("...") in except log.exception("cannot parse %r", raw)
log to a file logging.FileHandler FileHandler("output/run.log", encoding="utf-8")

The traceback of clean_sales.py from the lesson, as Python prints it. Your own project folder appears in place of /path/to/my-course:

Traceback (most recent call last):
File "/path/to/my-course/clean_sales.py", line 28, in <module>
print("Total revenue:", total_revenue(rows))
~~~~~~~~~~~~~^^^^^^
File "/path/to/my-course/clean_sales.py", line 24, in total_revenue
total += line_revenue(row)
~~~~~~~~~~~~^^^^^
File "/path/to/my-course/clean_sales.py", line 17, in line_revenue
price = parse_price(row["unit_price"])
File "/path/to/my-course/clean_sales.py", line 13, in parse_price
return float(text.removeprefix("$").replace(",", ""))
ValueError: could not convert string to float: 'N/A'
Order Look at Question
1 last line What went wrong? Type and message, often with the bad value
2 last frame Where was it raised? Skip library frames up to your own file
3 frames above How did the program get there? Where did the bad value come from?
4 carets ~~~^^^ Which part of the line was being evaluated? (Python 3.11+)
5 “The above exception was the direct cause…” A chained error: the lower block is the cause
6 “During handling of the above exception…” A second error inside an except block: often a bug in the handler
BaseException
├── KeyboardInterrupt Ctrl+C (do not catch by accident)
├── SystemExit sys.exit()
└── Exception base of every error you should handle
├── ArithmeticError
│ └── ZeroDivisionError revenue / 0
├── AssertionError assert False
├── AttributeError None.strip()
├── ImportError
│ └── ModuleNotFoundError import sklearnx
├── LookupError
│ ├── IndexError readings[40]
│ └── KeyError targets["west"]
├── NameError a typo: revenu
├── OSError
│ ├── FileNotFoundError open("data/sale.csv")
│ ├── PermissionError writing to a read-only folder
│ └── TimeoutError a network call that hangs
├── RuntimeError
│ ├── NotImplementedError a method left for subclasses
│ └── RecursionError recursion with no base case
├── StopIteration next() on an empty iterator
├── TypeError "Units: " + 3, len(42)
└── ValueError float("N/A"), int("2.5")
└── UnicodeError
└── UnicodeDecodeError latin-1 bytes read as UTF-8

ConnectionError and json.JSONDecodeError are subclasses too: ConnectionError of OSError, JSONDecodeError of ValueError. So except ValueError also catches bad JSON.

>>> import json
>>> issubclass(json.JSONDecodeError, ValueError), issubclass(ConnectionError, OSError)
(True, True)
>>> [cls.__name__ for cls in FileNotFoundError.__mro__]
['FileNotFoundError', 'OSError', 'Exception', 'BaseException', 'object']
Error Useful attributes
any exception err.args, str(err), type(err).__name__, err.__cause__, err.__context__, err.__notes__
KeyError err.args[0] is the missing key
OSError, FileNotFoundError err.filename, err.strerror, err.errno
json.JSONDecodeError err.lineno, err.colno, err.msg
UnicodeDecodeError err.encoding, err.start, err.reason
SyntaxError err.lineno, err.offset, err.text
def to_float(raw):
try:
value = float(raw) # only the line that can fail
except ValueError:
return None # expected problem: recover
else:
return round(value, 1) # runs only after a success
finally:
pass # always runs: cleanup goes here
print([to_float(x) for x in ["21.74", "n/a", ""]])
Output
[21.7, None, None]
Form Catches
except ValueError: ValueError and its subclasses
except (ValueError, TypeError) as err: either type
except LookupError: KeyError and IndexError
except Exception: every normal error, also your bugs: use only at the top level, log and re-raise
except: (bare) everything, even Ctrl+C: never
except* ValueError: the ValueErrors inside an ExceptionGroup (3.11+)

Clause order: try → (except if it raised a match, else if it raised nothing) → finally. The first matching except wins, so put specific types first.

def check_quantity(quantity, line_number):
if not 1 <= quantity <= 50:
raise ValueError(f"line {line_number}: quantity {quantity} is outside 1-50")
return quantity
try:
check_quantity(-3, 579)
except ValueError as err:
err.add_note("source: data/sales_raw.csv") # extra context, shown in tracebacks
print(err, err.__notes__)
Output
line 579: quantity -3 is outside 1-50 ['source: data/sales_raw.csv']
You write Effect
raise ValueError("msg") raise a new error
raise (inside except) re-raise the error being handled, with its traceback
raise New("msg") from err chain: New.__cause__ is err; traceback shows both, “direct cause”
raise New("msg") from None hide the original: traceback shows only New
raise New("msg") inside except implicit chain: __context__ is set; “During handling…”
err.add_note("text") add a line under the message (3.11+)
class ConfigError(Exception):
"""The config cannot be used."""
try:
try:
int("fifty")
except ValueError as err:
raise ConfigError("thresholds.max_quantity is not a number") from err
except ConfigError as err:
print(type(err.__cause__).__name__, "->", err)
Output
ValueError -> thresholds.max_quantity is not a number

A good message says where (file, line, column), what (the value) and why (the rule).

class DataValidationError(Exception):
"""Base class: a value in the input data breaks a rule."""
def __init__(self, message, *, column=None, line_number=None):
super().__init__(message) # keeps str(err) and the traceback message
self.column = column
self.line_number = line_number
class MissingColumnError(DataValidationError):
"""A required column is not in the header."""
class MissingValueError(DataValidationError):
"""A required cell is empty or holds a missing-value token."""
class InvalidValueError(DataValidationError):
"""A cell has a value, but the value breaks a rule."""
errors = [
MissingValueError("line 221: unit_price is missing", column="unit_price"),
InvalidValueError("line 579: quantity -3 is outside 1-50", column="quantity"),
]
for err in errors:
try:
raise err
except DataValidationError as caught: # one clause for the whole family
print(f"{type(caught).__name__:<18} {caught.column:<11} {caught}")
Output
MissingValueError unit_price line 221: unit_price is missing
InvalidValueError quantity line 579: quantity -3 is outside 1-50
Rule Why
one base class per library or project callers catch the whole family with one clause
subclass Exception, never BaseException except Exception must still catch it
name ends in Error matches the built-in names
a docstring, no pass needed the docstring is the class body
attributes for data (column, line_number) handlers count and route errors without parsing text
also subclass a built-in when it fits: class BadPriceError(DataValidationError, ValueError) old code that catches ValueError keeps working
errors = [ValueError("line 153: quantity 999"), KeyError("customer_id")]
try:
raise ExceptionGroup("validation failed", errors)
except* ValueError as group:
print("values:", [str(e) for e in group.exceptions])
except* KeyError as group:
print("keys:", [str(e) for e in group.exceptions])
Output
values: ['line 153: quantity 999']
keys: ["'customer_id'"]

Each except* clause takes the matching errors out of the group. Several clauses can run for one group. Unmatched errors travel up in a smaller group.

assert raise
Checks invariants of your own code data, files, arguments, user input
Under python -O removed still runs
Error type AssertionError the type that fits
Typical place tests, self-checks after a step start of a function, validation steps
prices = [224.1, 79.99, 103.96]
assert all(p > 0 for p in prices), "a price is not positive" # OK: silent
assert len(prices) == 3, f"expected 3 prices, got {len(prices)}"
print("checks passed")
Output
checks passed

Never write assert (cond, "msg"): a non-empty tuple is always true.

Step Tool
reproduce the smallest input that fails: 3 rows, not 20,000
read the traceback, bottom up
inspect print(f"{x=}"), print(repr(x)), print(type(x))
pause breakpoint(), python -m pdb script.py, an editor debugger
fix and lock in fix the cause, then add an assert or a test (module 14)
Command Does
p expr / pp expr print / pretty-print a value
n next line in this function
s step into a call
r run until the current function returns
c continue to the next breakpoint
unt 12 continue until line 12
l / ll list source around the line / the whole function
w where: show the call stack
u / d up to the caller / down again
b 12 / b 12, total < 0 breakpoint at line 12 / only when the condition is true
cl 1 clear breakpoint 1
display total show total after every step when it changes
interact open a full Python REPL in the current frame
q quit
h cmd help on a command
Terminal
python -m pdb script.py # start paused before the first statement
python -m pdb -c continue script.py # post-mortem: pause where it crashes
PYTHONBREAKPOINT=0 python script.py # skip every breakpoint() call

A pdb location line > /path/to/my-course/clean_sales.py(13)parse_price() means file, line, function. -> marks the next line to run. Name clashes: to print a variable called n or c, type p n.

Level Value Use
DEBUG 10 detail for developers
INFO 20 normal progress
WARNING 30 odd but handled (default level)
ERROR 40 a step failed
CRITICAL 50 the program cannot go on
import logging
logging.basicConfig( # once, in the main script
level=logging.INFO,
format="%(levelname)-7s %(name)s: %(message)s",
force=True, # replace an earlier setup (notebooks, repeated runs)
)
log = logging.getLogger("sales.loader") # in a module: getLogger(__name__)
log.debug("hidden: below INFO")
log.info("loaded %d rows from %s", 1200, "sales_raw.csv") # lazy %-style arguments
log.warning("%d rows with missing customer_id", 23)
try:
float("N/A")
except ValueError as err:
log.error("cannot parse unit_price: %s", err) # log.exception() adds the traceback
Output
INFO sales.loader: loaded 1200 rows from sales_raw.csv
WARNING sales.loader: 23 rows with missing customer_id
ERROR sales.loader: cannot parse unit_price: could not convert string to float: 'N/A'
Piece Job Example
Logger receives messages; has a name and a level logging.getLogger("sales.loader")
Handler sends them somewhere; has its own level StreamHandler() (stderr), FileHandler(path), RotatingFileHandler(path, maxBytes=..., backupCount=3)
Formatter lays out one line Formatter("%(asctime)s %(levelname)s [%(name)s] %(message)s")
propagate pass messages up to parent loggers set False when the logger has its own handlers
NullHandler swallow messages libraries add it, so they log nothing until the app configures logging
Format attribute Shows
%(asctime)s 2024-05-01 10:53:56,110 (datefmt= changes the layout)
%(levelname)s, %(levelname)-8s WARNING, padded
%(name)s logger name
%(message)s the message with its arguments
%(module)s, %(funcName)s, %(lineno)d where the call is
%(process)d, %(threadName)s for multi-process or threaded programs (module 15)

Two handlers with different levels:

setup_logging.py
log = logging.getLogger("sales.validate")
log.setLevel(logging.DEBUG) # let everything through to the handlers
log.propagate = False # do not print twice through the root logger
console = logging.StreamHandler()
console.setLevel(logging.WARNING) # terminal: warnings and worse
console.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
to_file = logging.FileHandler("output/validation.log", mode="w", encoding="utf-8")
to_file.setLevel(logging.DEBUG) # file: everything, with a timestamp
to_file.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(message)s"))
log.addHandler(console)
log.addHandler(to_file)
print() logging
always on switch levels without editing code
goes to stdout, mixed with data output goes to stderr or files
no time, level or origin format with time, level, logger name, line
fine for quick checks and real program output for status, warnings and errors of programs that run unattended
  • Read a traceback from the bottom. The top frame is the start of the program.
  • The last frame shows where Python gave up, not always where the bad value entered. Walk up.
  • A SyntaxError cannot be caught by a try in the same file. Python stops before any line runs.
  • except: and except Exception: hide your own typos. Catch the specific type.
  • Keep the try block to the line that can fail. Put the follow-up code in else.
  • except Exception before except ValueError makes the second clause dead code.
  • err is deleted at the end of its except block. Copy what you need: saved = err.
  • finally runs even after return. A return inside finally swallows exceptions: never do it.
  • A KeyError message is only the key: KeyError: 'west'. Print the dict’s keys to compare.
  • json.JSONDecodeError and UnicodeDecodeError are ValueErrors. except ValueError catches them too.
  • Returning 0 or "" for bad data hides it. Raise, or return None and count the skips.
  • assert disappears under python -O. Never use it to validate data.
  • assert (x > 0, "msg") is always true. Drop the parentheses.
  • breakpoint() left in a scheduled job makes it wait forever. Ruff rule T100 finds it.
  • pdb commands win over variable names: n steps. Use p n to print a variable n.
  • logging shows nothing below WARNING until you configure a level.
  • basicConfig() does nothing if the root logger already has handlers. Pass force=True or configure once.
  • Duplicate log lines: a named logger with its own handler also propagates to the root handler. Set propagate = False.
  • log.debug(f"...") builds the text even when DEBUG is off. Use log.debug("row %s", row).
  • log.error(err) loses the traceback. Use log.exception("what failed") inside except.
  • Never log secrets (passwords, API keys, tokens). Log files are read by many people and tools.