Sub topic 3
Re-raising and Logging Exceptions
Assume you can write functions, use basic inheritance, and read a simple traceback. This chapter focuses on preserving errors while adding useful context.
Re-raising and chaining
Log an exception when you can add useful diagnostic information. Then use a bare raise to preserve the original exception and traceback.
import logging
logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger(__name__)
def process(job):
try:
job()
except Exception:
logger.exception("Job failed")
raiselogger.exception() includes the traceback. Avoid catching Exception unless this is a boundary where you will log and pass the error onward.
Use raise ... from ... when translating a low-level error into an application-level error. The original error remains available as __cause__.
class ConfigError(Exception):
"""Raised when configuration is invalid."""
def load_port(raw):
try:
return int(raw)
except ValueError as exc:
raise ConfigError(f"Invalid port: {raw!r}") from excThe caller sees ConfigError, while the traceback explains that ValueError caused it.
Custom exceptions and context managers
Custom exception classes give callers a stable, specific type to catch. Usually, inherit from Exception, not directly from BaseException.
A context manager controls setup and cleanup around a with statement. It replaces many manual try/finally blocks.
from contextlib import contextmanager
@contextmanager
def opened(path):
file = open(path)
try:
yield file
finally:
file.close()
with opened("notes.txt") as file:
first_line = file.readline()The cleanup runs even when reading raises an exception. For ordinary files, use Python’s built-in open() context manager directly.
Best practices and exception groups
Use narrow handlers and catch the errors you expect. EAFP means “easier to ask forgiveness than permission”: attempt the operation, then handle its known failure.
try:
port = int(text)
except ValueError:
port = 8080Avoid bare except: clauses. They also catch KeyboardInterrupt and SystemExit. Do not silently ignore errors or log an error and then continue as if the operation succeeded.
Python 3.11 introduced ExceptionGroup, which holds several failures. except* handles matching members independently.
try:
raise ExceptionGroup("batch failed", [ValueError("a"), TypeError("b")])
except* ValueError as group:
print(group.exceptions)
except* TypeError as group:
print(group.exceptions)Exercise
Why use a bare raise after logging instead of raise exc?
Show answer
A bare raise preserves the active exception and its original traceback, making the failure location easier to diagnose.