Skip to content

Errors, debugging and logging

Everything about things going wrong: the exception hierarchy, how to catch, raise, chain and group exceptions, how to read a traceback, how to drive pdb, how to set up logging, and how to work with warnings. Every runnable block is checked against its output.

I want to… Use… Example
handle one error type try / except E as exc: except ValueError as exc:
handle several types the same way a tuple except (KeyError, IndexError):
run code only if no error happened else: keeps the try block small
always run clean-up finally: or a with block close, unlock, delete temp files
signal a bad argument raise ValueError("...") wrong value, right type
signal a wrong type raise TypeError("...")
re-raise the current error bare raise inside except keeps the traceback
wrap a low-level error raise NewError(...) from exc the cause is kept
hide the original error raise NewError(...) from None cleaner messages for users
add context to an error exc.add_note("row 42") (3.11+) shown under the message
define my own error class AppError(Exception): one base class per package
raise several errors at once ExceptionGroup("msg", [e1, e2]) validation, concurrent tasks
handle parts of a group except* ValueError as eg: each matching sub-group
ignore an expected error contextlib.suppress(E) with suppress(FileNotFoundError):
get the traceback as text traceback.format_exc() in an except block
log an error with its traceback log.exception("msg") inside except
check an internal assumption assert cond, "msg" not for user input; -O removes it
pause in the debugger breakpoint() then p x, n, s, c
debug after a crash python -m pdb -c continue script.py or pdb.pm() in the REPL
turn breakpoints off PYTHONBREAKPOINT=0 environment variable
print a variable with its name print(f"{x=}") x=42
start logging in a script logging.basicConfig(level=logging.INFO) once, at startup
get a logger in a module log = logging.getLogger(__name__)
log with lazy arguments log.info("loaded %d rows", n) not an f-string
send logs to a file logging.FileHandler(path) or basicConfig(filename=...)
warn about deprecated use warnings.warn("...", DeprecationWarning, stacklevel=2) points at the caller
turn warnings into errors python -W error script.py or warnings.simplefilter("error")
silence one known warning warnings.catch_warnings() + filterwarnings("ignore", ...) narrow: category and message
record warnings in a test warnings.catch_warnings(record=True) pytest.warns(...) in pytest
exit with a status code sys.exit(1) or raise SystemExit("message")
BaseException
├── SystemExit, KeyboardInterrupt, GeneratorExit (do not catch these by accident)
├── BaseExceptionGroup
│ └── ExceptionGroup (also an Exception)
└── Exception
├── ArithmeticError: ZeroDivisionError, OverflowError, FloatingPointError
├── LookupError: IndexError, KeyError
├── ValueError
│ └── UnicodeError: UnicodeDecodeError, UnicodeEncodeError
├── TypeError, AttributeError, AssertionError, EOFError, BufferError
├── NameError
│ └── UnboundLocalError
├── ImportError
│ └── ModuleNotFoundError
├── OSError (alias IOError)
│ ├── FileNotFoundError, FileExistsError, PermissionError
│ ├── IsADirectoryError, NotADirectoryError, TimeoutError
│ └── ConnectionError: ConnectionRefusedError, ConnectionResetError, BrokenPipeError
├── RuntimeError: RecursionError, NotImplementedError, PythonFinalizationError (3.13)
├── StopIteration, StopAsyncIteration
├── SyntaxError
│ └── IndentationError: TabError
├── MemoryError, ReferenceError, SystemError
└── Warning: UserWarning, DeprecationWarning, FutureWarning, RuntimeWarning, ...
Exception Typical cause Example message
ValueError right type, bad value invalid literal for int() with base 10: 'abc'
TypeError wrong type or wrong number of arguments unsupported operand type(s) for +: 'int' and 'str'
KeyError missing dict key 'store_id'
IndexError index past the end list index out of range
AttributeError missing attribute or method; often None 'NoneType' object has no attribute 'strip'
NameError typo or not defined yet name 'totl' is not defined (3.10+ adds “Did you mean” hints)
UnboundLocalError assignment makes the name local cannot access local variable 'x' where it is not associated with a value
ZeroDivisionError /, // or % by 0 division by zero
FileNotFoundError wrong path or working folder [Errno 2] No such file or directory: 'data.csv'
PermissionError no rights, or file open in another program [Errno 13] Permission denied: ...
UnicodeDecodeError the file is not in the given encoding 'utf-8' codec can't decode byte 0xe9 ...
ModuleNotFoundError package not installed in this environment No module named 'pandas'
RecursionError no base case maximum recursion depth exceeded
StopIteration next() on an exhausted iterator
AssertionError an assert failed the assert message
NotImplementedError abstract method or unfinished branch
json.JSONDecodeError invalid JSON (a ValueError) Expecting value: line 1 column 1 (char 0)
csv.Error, sqlite3.Error, httpx.HTTPError library errors catch the library’s base class
for exc_type in (FileNotFoundError, KeyError, UnicodeDecodeError, ModuleNotFoundError):
print(" -> ".join(c.__name__ for c in exc_type.__mro__[:-2]))
print(issubclass(KeyboardInterrupt, Exception), issubclass(OSError, Exception))
Output
FileNotFoundError -> OSError -> Exception
KeyError -> LookupError -> Exception
UnicodeDecodeError -> UnicodeError -> ValueError -> Exception
ModuleNotFoundError -> ImportError -> Exception
False True
def safe_ratio(a, b):
try:
result = a / b # only the code that can fail
except ZeroDivisionError:
print(" except: b is 0")
return None
except TypeError as exc:
print(" except:", exc)
return None
else:
print(" else: no error") # runs only when try succeeded
return round(result, 2)
finally:
print(" finally: always") # runs even after return
for args in [(1, 3), (1, 0), (1, "x")]:
print(args, "->", safe_ratio(*args))
Output
else: no error
finally: always
(1, 3) -> 0.33
except: b is 0
finally: always
(1, 0) -> None
except: unsupported operand type(s) for /: 'int' and 'str'
finally: always
(1, 'x') -> None
Clause Runs when Use
try first only the line(s) that can fail
except E E or a subclass was raised the first matching clause wins; order from specific to general
except E as exc as above; exc is deleted after the block read exc.args, str(exc)
else try finished with no exception code that depends on success but must not be guarded
finally always: after success, error, return, break clean-up; never return from here
bare except: anything, even KeyboardInterrupt avoid; use except Exception: at the top level only
def parse_price(text):
try:
return float(text.removeprefix("$"))
except ValueError as exc:
raise ValueError(f"bad price {text!r}") from exc # explicit cause
try:
parse_price("N/A")
except ValueError as exc:
print(exc, "| cause:", repr(exc.__cause__))
try:
try:
store = {}["store"]
except KeyError:
raise LookupError("store not configured") from None # hide the KeyError
except LookupError as exc:
print(exc, exc.__cause__, exc.__suppress_context__)
try:
int("x")
except ValueError as exc:
exc.add_note("while reading row 42 of data/sales.csv") # 3.11+
print(exc.__notes__)
Output
bad price 'N/A' | cause: ValueError("could not convert string to float: 'N/A'")
store not configured None True
['while reading row 42 of data/sales.csv']
Form Traceback shows Use
raise the original error and traceback log, then re-raise
raise New(...) inside except both, “During handling of the above exception, another exception occurred” usually a bug in the handler
raise New(...) from exc both, “The above exception was the direct cause of the following exception” translate low-level errors
raise New(...) from None only the new error user-facing messages
exc.add_note(text) the note under the message add the row, file or id
raise ValueError (a class) same as ValueError() prefer a message
class PipelineError(Exception):
"""Base class: callers can catch every error of this package."""
class ValidationError(PipelineError):
def __init__(self, column, value, reason):
super().__init__(f"{column}={value!r}: {reason}") # sets str(exc)
self.column, self.value, self.reason = column, value, reason
class MissingFileError(PipelineError, FileNotFoundError):
"""Also a FileNotFoundError, so generic handlers still work."""
try:
raise ValidationError("quantity", -3, "must be >= 0")
except PipelineError as exc:
print(type(exc).__name__, exc, exc.column)
print(issubclass(MissingFileError, OSError))
Output
ValidationError quantity=-3: must be >= 0 quantity
True
Rule Detail
inherit from Exception never from BaseException
name ends with Error ConfigError, ValidationError
one base per package callers write except mypackage.Error:
call super().__init__(message) so str(exc) and pickling work
store data as attributes handlers should not parse the message
also subclass a built-in when it fits class NotFound(MyError, KeyError)
def validate(row):
errors = []
if not row["id"].startswith("O"):
errors.append(ValueError(f"bad id {row['id']!r}"))
if row["qty"] < 0:
errors.append(ValueError(f"negative qty {row['qty']}"))
if "price" not in row:
errors.append(KeyError("price"))
if errors:
raise ExceptionGroup("row invalid", errors)
try:
validate({"id": "X1", "qty": -2})
except* ValueError as group: # every ValueError of the group
print("values:", [str(e) for e in group.exceptions])
except* KeyError as group: # the KeyErrors; both clauses can run
print("keys:", [str(e) for e in group.exceptions])
Output
values: ["bad id 'X1'", 'negative qty -2']
keys: ["'price'"]
Fact Detail
ExceptionGroup(msg, [excs]) holds Exception subclasses; BaseExceptionGroup for others
except* T gets a sub-group with the matching exceptions; several clauses can run
unmatched exceptions re-raised in a new group after the except* clauses
plain except ExceptionGroup catches the whole group
eg.subgroup(pred), eg.split(T) filter a group by hand
where they come from asyncio.TaskGroup, trio, your own validation
no mixing one try uses except or except*, not both

load_prices.py:

load_prices.py
def parse_price(text):
return float(text.removeprefix("$"))
def load(rows):
return [parse_price(row["price"]) for row in rows]
def main():
rows = [{"price": "$4.99"}, {"price": "N/A"}]
try:
prices = load(rows)
except ValueError as exc:
raise RuntimeError("cannot load prices") from exc
print(sum(prices))
main()

What Python 3.13 prints (your folder appears in place of /path/to/my-course):

Traceback (most recent call last):
File "/path/to/my-course/load_prices.py", line 12, in main
prices = load(rows)
File "/path/to/my-course/load_prices.py", line 6, in load
return [parse_price(row["price"]) for row in rows]
~~~~~~~~~~~^^^^^^^^^^^^^^
File "/path/to/my-course/load_prices.py", line 2, in parse_price
return float(text.removeprefix("$"))
ValueError: could not convert string to float: 'N/A'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/path/to/my-course/load_prices.py", line 18, in <module>
main()
~~~~^^
File "/path/to/my-course/load_prices.py", line 14, in main
raise RuntimeError("cannot load prices") from exc
RuntimeError: cannot load prices
Step Look at Question
1 the very last line what went wrong: type and message
2 the last frame of your code where it was raised (skip library frames)
3 frames above it, bottom to top how the program got there; where the bad value came from
4 ~~~^^^ markers (3.11+) which part of the line ran
5 “direct cause” a chained error (from exc): the first block is the root cause
6 “During handling of the above exception” a second error inside an except block
7 +-+--- boxes an exception group: one box per sub-exception

The traceback module gives the same data as values:

import traceback
def parse_price(text):
return float(text.removeprefix("$"))
try:
prices = [parse_price(t) for t in ["$4.99", "N/A"]]
except ValueError as exc:
for frame in traceback.extract_tb(exc.__traceback__):
print(f"{frame.name:<12} line {frame.lineno}: {frame.line}")
print(traceback.format_exception_only(exc)[-1], end="")
Output
<module> line 9: prices = [parse_price(t) for t in ["$4.99", "N/A"]]
parse_price line 5: return float(text.removeprefix("$"))
ValueError: could not convert string to float: 'N/A'
Command Does
h / h cmd help
p expr / pp expr print / pretty-print a value
n next line (step over calls)
s step into a call
r continue until the current function returns
c continue to the next breakpoint
unt N continue until line N (leaves loops)
j N jump to line N (in the current function)
l / ll list source around the current line / the whole function
w where: the call stack
u / d move up to the caller / down again
b N, b file.py:N, b func set a breakpoint
b N, cond conditional breakpoint: b 24, total < 0
tbreak N one-time breakpoint
cl N / disable N / enable N clear / disable / enable breakpoint N
a arguments of the current function
display expr show expr whenever it changes
!stmt run a Python statement (!n = 3 when n is a variable)
interact a full REPL in the current frame
q quit
Terminal
python -m pdb script.py # start paused at the first line
python -m pdb -c continue script.py # run; pause where it crashes (post-mortem)
PYTHONBREAKPOINT=0 python script.py # ignore every breakpoint() call
python -X dev script.py # dev mode: more warnings and checks
python -i script.py # REPL after a crash; then: import pdb; pdb.pm()
Technique When
print(f"{x=}"), print(repr(x), type(x)) quick checks; hidden spaces and types
breakpoint() pause at a line and look around
editor debugger (VS Code, PyCharm) breakpoints, watches, the same pdb ideas with a UI
assert invariants catch a bad state early, near the cause
smallest failing input 3 rows, not 20,000
logging at DEBUG long-running or unattended programs
a test that reproduces the bug fix it once, keep it fixed
%debug in Jupyter post-mortem after a failed cell
Level Value Use
DEBUG 10 detail for developers
INFO 20 normal progress
WARNING 30 something odd, handled; the default threshold
ERROR 40 an operation failed
CRITICAL 50 the program cannot continue
import logging
logging.basicConfig(
level=logging.INFO, # show INFO and above
format="%(levelname)-8s %(name)s: %(message)s", # add %(asctime)s in real apps
force=True, # replace any earlier configuration
)
log = logging.getLogger("sales.loader") # in modules: logging.getLogger(__name__)
log.debug("not shown: below the level")
log.info("loaded %d rows from %s", 20228, "data/sales.csv") # lazy formatting
log.warning("%d rows without customer_id", 23)
try:
ratio = 1 / 0
except ZeroDivisionError as exc:
log.error("ratio failed: %s", exc) # log.exception() also prints the traceback
logging.getLogger("sales").setLevel(logging.ERROR) # quiet a whole logger tree
log.warning("not shown: the parent logger is at ERROR")
Output
INFO sales.loader: loaded 20228 rows from data/sales.csv
WARNING sales.loader: 23 rows without customer_id
ERROR sales.loader: ratio failed: division by zero
Piece Job Example
logger named source with a level; names form a tree (a.b is a child of a) logging.getLogger(__name__)
handler sends records somewhere; has its own level StreamHandler(), FileHandler(path), RotatingFileHandler(path, maxBytes=..., backupCount=3)
formatter the line layout Formatter("%(asctime)s %(levelname)s %(name)s %(message)s")
filter drop or edit records handler.addFilter(func)
propagate pass records up to parent handlers False to avoid double lines
NullHandler libraries add it so they stay silent until the app configures logging logging.getLogger(__name__).addHandler(logging.NullHandler())
Format field Shows
%(asctime)s the time (datefmt="%Y-%m-%d %H:%M:%S" to change it)
%(levelname)s, %(levelname)-8s the level, padded
%(name)s the logger name
%(message)s the message with arguments
%(module)s, %(funcName)s, %(lineno)d where the call is
%(process)d, %(threadName)s process and thread
logging_config.py
import logging.config
logging.config.dictConfig({
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"plain": {"format": "%(asctime)s %(levelname)-8s %(name)s: %(message)s"},
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"level": "INFO",
"formatter": "plain",
},
"file": {
"class": "logging.handlers.RotatingFileHandler",
"filename": "output/app.log",
"maxBytes": 1_000_000,
"backupCount": 3,
"formatter": "plain",
"encoding": "utf-8",
},
},
"root": {"level": "DEBUG", "handlers": ["console", "file"]},
})
Category Shown by default Use
UserWarning yes the default for warnings.warn
DeprecationWarning only in __main__ and tests for other developers: an API will go away
FutureWarning yes for end users: behavior will change (pandas uses it)
PendingDeprecationWarning no a future deprecation
RuntimeWarning yes dubious run-time behavior (NumPy overflow, never-awaited coroutines)
SyntaxWarning yes dubious syntax: "\d" invalid escape (3.12+)
ResourceWarning no (shown with -X dev) unclosed files and sockets
Action (filterwarnings, -W) Effect
"default" show once per location
"error" raise the warning as an exception
"ignore" never show
"always" show every time
"once" show only the first time
import warnings
def old_api():
message = "old_api() is deprecated; use new_api()"
warnings.warn(message, DeprecationWarning, stacklevel=2) # point at the caller
return 42
with warnings.catch_warnings(record=True) as caught: # filters restored afterward
warnings.simplefilter("always")
old_api()
print(len(caught), caught[0].category.__name__, caught[0].message)
with warnings.catch_warnings():
warnings.simplefilter("error") # warnings become exceptions in this block
try:
old_api()
except DeprecationWarning as exc:
print("raised:", exc)
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="old_api", category=DeprecationWarning)
print(old_api()) # silenced: narrow by message and category
Output
1 DeprecationWarning old_api() is deprecated; use new_api()
raised: old_api() is deprecated; use new_api()
42
Terminal
python -W error script.py # every warning is an error
python -W "ignore::DeprecationWarning" script.py # action:message:category:module:line
PYTHONWARNINGS=default python script.py # the same through the environment
pytest -W error::FutureWarning # fail tests on FutureWarning
Trap Symptom Fix
bare except: or except Exception: pass bugs and Ctrl+C vanish catch the narrow type; log what you swallow
a big try block the handler catches errors from the wrong line keep only the failing call in try; use else
except (A, B) written as except A, B SyntaxError parentheses are required
general except before specific ones the specific clause never runs order from specific to general
raise New(...) inside except without from confusing “During handling…” traceback from exc or from None
return in finally swallows the exception (SyntaxWarning in 3.14) never return or break in finally
exc used after the except block NameError: it is deleted copy it: error = exc
catching StopIteration or KeyboardInterrupt by accident loops end or Ctrl+C is ignored catch Exception subclasses only
assert for input validation skipped with python -O if not ok: raise ValueError(...)
assert (x, "msg") always passes: a non-empty tuple assert x, "msg"
log.info(f"... {x}") formats even when INFO is off log.info("... %s", x)
logging.basicConfig called twice the second call does nothing call once at startup, or pass force=True
print for errors goes to stdout, no level or time logging, or print(..., file=sys.stderr)
duplicate log lines a handler on the logger and on the root log.propagate = False, or handlers only on the root
library code calls basicConfig overrides the app’s setup libraries only getLogger(__name__) + NullHandler
warnings.filterwarnings("ignore") globally hides real problems narrow by category, message and module, inside catch_warnings()
warnings.warn without stacklevel=2 the warning points at your library line stacklevel=2 points at the caller
exception messages differ by version hints and wording change between 3.12 and 3.13 match on the type, not the message text