Code Reference

Exceptions

Python · Reference cheat sheet

Exceptions

Python · Reference cheat sheet


📋 Overview

Exceptions signal error conditions. Use try / except / else / finally, raise with raise, and chain with raise ... from. Prefer built-in types or small custom hierarchies over bare except:.

🔧 Core concepts

ConstructRole
tryGuarded block
except Exc as eHandle specific type(s)
except* Exception groups (3.11+)
elseRuns if no exception
finallyAlways runs (cleanup)
raiseRaise / re-raise
raise X from eExplicit chaining
ExceptionGroupMultiple errors (3.11+)

Catch narrow types first. BaseException includes KeyboardInterrupt / SystemExit — usually do not catch those.

💡 Examples

Try / except / else / finally:

def load(path: str) -> str:
    try:
        with open(path, encoding="utf-8") as f:
            data = f.read()
    except FileNotFoundError:
        return ""
    except OSError as e:
        raise RuntimeError(f"read failed: {path}") from e
    else:
        return data.strip()
    finally:
        pass  # close handled by `with`

Custom exception:

class AppError(Exception):
    """Base app error."""

class NotFoundError(AppError):
    def __init__(self, entity: str, key: object) -> None:
        super().__init__(f"{entity} not found: {key!r}")
        self.entity = entity
        self.key = key

raise NotFoundError("user", 42)

Exception groups (3.11+):

def run_all() -> None:
    errors: list[Exception] = []
    for i in (0, 1):
        try:
            if i == 0:
                raise ValueError("bad")
            raise TypeError("wrong")
        except Exception as e:
            errors.append(e)
    if errors:
        raise ExceptionGroup("batch failed", errors)

try:
    run_all()
except* ValueError as eg:
    print("values", eg.exceptions)
except* TypeError as eg:
    print("types", eg.exceptions)

⚠️ Pitfalls

  • Bare except: or except Exception can hide bugs — be specific.
  • Catching and ignoring without logging loses diagnostics.
  • finally with return can swallow exceptions — avoid returning there.
  • Use raise ... from e (or from None) intentionally for traceback clarity.
  • Validating with exceptions in hot loops can be slower than checks.

On this page