Python · Chapter 9 of 21
Python exceptions: try, except, raise, logging and pdb
15 min study · Examples checked with Python 3.14 and 3.15 ·
Programs that touch the outside world meet bad input, missing files and timeouts. Python reports these by raising exceptions. This chapter covers handling the ones you expect, raising your own, keeping a record of failures with logging, testing that errors happen when they should, and finding the cause of the ones you didn’t expect.
Catch the exception you expect
def parse_count(text: str) -> int:
try:
count = int(text)
except ValueError:
raise ValueError(f"{text!r} is not a whole number") from None
if not 1 <= count <= 100:
raise ValueError(f"{count} is outside 1-100")
return count
for text in ["3", "three", "0"]:
try:
count = parse_count(text)
except ValueError as error:
print("Rejected:", error) # 'three' is not a whole number / 0 is outside 1-100
else:
print("Accepted:", count) # 3
When an exception is raised, Python abandons the current code and looks for an except clause that matches the exception’s type, first in the current function, then in its caller, and so on up the call stack. If none matches, the program stops with a traceback. as error gives you the exception object; str(error) is its message.
Keep the try block small, ideally the single call that can fail; a large one can catch an error from a line you never meant to protect. For the same reason, catch specific types. A bare except: even catches KeyboardInterrupt (Ctrl+C) and SystemExit, which makes a program hard to stop. except Exception: is acceptable at the very top of a program or a request handler, where the job is to log the failure and return an error page, not to continue as if nothing happened.
The exception hierarchy
Exceptions are classes arranged in a hierarchy, and an except clause also catches subclasses of the type it names. ArithmeticError covers ZeroDivisionError; LookupError covers KeyError and IndexError; OSError covers FileNotFoundError, PermissionError and timeouts.
A try statement can have several except clauses, for example one for ValueError (“not a number”) and one for ZeroDivisionError (“cannot divide by zero”) around float(a) / float(b). Python tries the clauses in order and runs the first match, so put specific types before general ones. When several types get the same treatment, list them together: except (KeyError, IndexError):. Since Python 3.14 the parentheses can be left out when there is no as clause.
What you do in the handler matters as much as what you catch. Recover if you can (use a default, ask again, retry), translate the error into one that makes sense to your caller, or let it propagate. Catching an exception, printing it and returning a value that looks like success is the worst option: the program carries on with wrong data.
else, finally and cleanup
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
path = Path(folder) / "count.txt"
path.write_text("42", encoding="utf-8")
try:
text = path.read_text(encoding="utf-8")
except OSError as error:
print("cannot read:", error)
else:
print("read", repr(text))
finally:
print("done")
else runs only if the try block raised nothing; it keeps code that should not be protected out of the try. finally always runs when the statement is left, whether normally, through an exception or through a return. Do not return from inside finally: it silently discards any exception in flight, and recent Python versions warn about it. For releasing resources such as files and locks, a with statement (used twice above) is shorter and safer than finally.
Raise your own exceptions
Raise an exception when a function cannot do what its name promises. For rules of your own application, define exception classes so callers can catch exactly those:
class EnrolmentError(Exception):
"""A request to join a course was refused."""
class CourseFullError(EnrolmentError):
def __init__(self, course: str, capacity: int):
super().__init__(f"{course} is full ({capacity} seats)")
self.course = course
self.capacity = capacity
def enrol(course: str, taken: int, capacity: int) -> int:
if taken >= capacity:
raise CourseFullError(course, capacity)
return taken + 1
try:
enrol("Python", 30, 30)
except EnrolmentError as error:
print(error, "|", type(error).__name__, error.capacity)
# Python is full (30 seats) | CourseFullError 30
Derive from Exception, not BaseException. A base class for your package (EnrolmentError) lets callers catch all of your errors at once, and subclasses carry useful attributes. When you translate one exception into another, raise NewError(...) from error records the original as the cause, so both appear in the traceback. from None hides the cause when it adds nothing, as in parse_count. Inside an except block, a bare raise re-raises the current exception unchanged.
An assert statement is different: it checks a condition that should be impossible if your code is correct, and Python skips asserts entirely when run with -O. Use it for internal sanity checks and tests, never to validate user input.
Log failures instead of printing them
print is fine while you experiment, but a real program should report problems through the logging module. Log records have a level, a timestamp and a source, and the destination (terminal, file, monitoring service) is configured in one place.
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
log = logging.getLogger("enrolment")
log.info("starting import of %d rows", 3)
try:
enrol("Python", 30, 30)
except CourseFullError:
log.exception("could not enrol") # ERROR level, plus the traceback
Pass values as arguments ("%d rows", 3) rather than formatting the string yourself; the message is only built if the record is actually emitted. log.exception inside an except block adds the full traceback, which is exactly what you need when investigating a failure later. Libraries should only create loggers with logging.getLogger(__name__); configuring output with basicConfig is the application’s job.
Test the error paths
A function’s failures are part of its behaviour, so test them. With pytest, the most widely used test runner, a test file looks like this:
import pytest
from enrolment import parse_count
def test_accepts_a_number():
assert parse_count("7") == 7
def test_rejects_text():
with pytest.raises(ValueError, match="not a whole number"):
parse_count("seven")
Install pytest into your project’s environment and run python -m pytest; it finds files named test_*.py and functions named test_*. pytest.raises fails the test unless the block raises that exception with a matching message. The standard library’s unittest offers the same with self.assertRaises.
Find the cause with the debugger
When a failure surprises you, look at the traceback first (chapter 1 shows how to read it), then inspect the program’s state where it went wrong instead of guessing. Put breakpoint() on the line before the failure and run the script; Python stops there and opens pdb, its built-in debugger:
def total_with_tax(prices, rate):
subtotal = sum(prices)
breakpoint()
return subtotal * (1 - rate) # bug: should be 1 + rate
print(total_with_tax([10, 20], 0.2))
At the (Pdb) prompt, p subtotal prints a value, n runs the next line, s steps into a call, c continues, w shows the call stack, l lists the surrounding code and q quits. You can also run any script under the debugger with python -m pdb script.py, which stops when an uncaught exception occurs. Remove breakpoint() calls before committing code.
Practice
Extend parse_count so that it also rejects empty input with its own message, and add a CountError(ValueError) class used for all three cases. Then debug total_with_tax from the last section: stop at the breakpoint, print subtotal and the expression subtotal * (1 - rate), and fix the formula.
Answer check: parse_count("") should raise CountError with a message such as “empty input”, and because CountError subclasses ValueError, existing except ValueError handlers keep working. With the fix, the total is 36.0, while the bug gives 24.0.
Summary
Catch specific exceptions close to where you can do something useful, keep try blocks small, use else for the success path and with or finally for cleanup. Raise your own exception classes, chain causes with from, log failures with logging instead of printing them, test the error paths, and debug with breakpoint() rather than guesses.