"> ">
⚑ Track 04 β€” Mid-Level Masterclass

Advanced Exception Architecture & Exception Chaining

Design resilient error handling with custom domain exceptions, explicit exception chaining (`raise NewError from original_err`), and modern Python 3.11+ Exception Groups (`except*`).

πŸ‘οΈ Views: 3,354 Page Views
⚑ Mid-Level Python Interactive Studio

Interactive Sandbox Studio: 4 Tracks & 26 Competencies

πŸ‘οΈ 3,354 Total Page Views

Switch tracks and select any of the 26 core topics below to run production Python code, inspect CPython memory mechanics, and execute unit test assertion suites in real time.

πŸ“Œ Select Topic (26 Total): Showing 1 Topic for Track 04
⚑ Topic 26 of 26 ⏱️ 5 min interactive
Module 26 of 26

26. Custom Exception Hierarchy & Exception Chaining

Create custom domain exceptions by inheriting from Exception. Use raise NewError(...) from orig_err to preserve original tracebacks cleanly.

πŸ’‘ Core Engineering Principles

  • Domain Exceptions: Subclass Exception to define domain-specific errors.
  • Explicit Chaining: raise ... from e sets __cause__ to link causal errors.
  • Implicit Chaining: Automatic __context__ association during exception handling.
middle_exceptions_chaining.py
Ready (Python 3.13 Active)
πŸ–₯️ Execution Output & Test Results stdout
Click "β–Ά Run Code" to execute this Mid-Level Python module or "πŸ§ͺ Run Unit Tests" to verify with pytest.
🚨 Mid-Level Python Complete Error List (16 Errors, Root Reasons & Solutions) β€” Click to Expand
🚨 Complete Python Error List, Root Causes & Production Solutions

⚑ Mid-Level Python Architecture & OOP Error Encyclopedia

Every Mid-Level (16) Python exception explained with its exact root reason, step-by-step fix, side-by-side ❌ Broken vs. βœ… Fixed Code, and 1-click Live Python Execution.

πŸ”
Showing Level Errors
πŸ“‹ Quick-Reference Summary Table: Mid-Level Python Errors (16)
Level Exception / Error Root Reason (Why It Happens) Production Solution (How to Fix)
Mid-LevelUnboundLocalError: cannot access local variable before assignmentWhen Python compiles a function body, any variable assigned anywhere inside the function (e.g., count += 1) is marked as a LOCAL variable for the entire function. Reading it before that assignment raises UnboundLocalError even if a global or enclosing variable of the same name exists.Pass state explicitly as function arguments, or declare 'nonlocal var' (for enclosing closures) or 'global var' (for module globals) before mutating.
Mid-LevelMutable Default Argument Trap (Shared State Bug)Default parameter values in Python are evaluated ONCE when the 'def' statement is executed, not each time the function is called. Using a mutable default (def append_tag(tag, tags=[]):) causes every caller that omits 'tags' to mutate the exact same list object in memory!Always use None as the default value (tags: list[str] | None = None) and instantiate a fresh list inside the function body.
Mid-LevelValueError: mutable default <class 'list'> for field is not allowedPython's @dataclass explicitly raises a ValueError at class creation time if you assign a mutable default (like list, dict, or set) directly to a field, protecting you from shared mutable state across instances.Import 'field' from dataclasses and use field(default_factory=list) or field(default_factory=dict).
Mid-Leveldataclasses.FrozenInstanceError: cannot assign to fieldAttempting to mutate an attribute on a dataclass decorated with @dataclass(frozen=True). Frozen dataclasses override __setattr__ to enforce immutability and hashability.Use dataclasses.replace(instance, field=new_val) to create a new updated instance while preserving immutability.
Mid-LevelRuntimeError: dictionary / set changed size during iterationAdding or deleting keys from a dictionary or set while iterating directly over its live view (for k in my_dict:) invalidates internal hash table pointers and raises RuntimeError.Iterate over a snapshot list of keys (for k in list(my_dict):) when deleting in place, or build a filtered dictionary using a dict comprehension.
Mid-LevelLate-Binding Closure Trap in Loops (Lambdas / Functions)Closures capture variables by reference (cell objects), not by value. Creating functions or lambdas inside a loop (e.g., [lambda x: x * i for i in range(4)]) causes all functions to look up the final value of 'i' after the loop finishes!Bind the loop variable eagerly as a default parameter (lambda x, i=i: x * i) or use functools.partial.
Mid-LevelShallow Copy Nested Mutation Bug (copy.copy vs copy.deepcopy)A shallow copy (dict.copy(), list[:], or copy.copy()) only duplicates the outer container; nested lists or dicts inside still point to the exact same memory addresses (id()).Use copy.deepcopy(obj) when cloning nested data structures so inner mutable objects are recursively duplicated.
Mid-LevelTypeError: Can't instantiate abstract class with abstract methodA subclass inheriting from an Abstract Base Class (abc.ABC) failed to implement one or more methods decorated with @abstractmethod.Implement every @abstractmethod defined on the parent ABC with a matching signature in the concrete subclass.
Mid-LevelTypeError: Cannot create a consistent method resolution order (MRO)In multiple inheritance, listing a base class before its own subclass (e.g., class C(Base, SubOfBase):) violates Python's C3 Linearization monotonicity rule because Base would precede SubOfBase.Always order more-specific subclasses BEFORE their parent base classes in the inheritance tuple, or favor composition over deep multiple inheritance.
Mid-LevelRecursionError in @property Getter/SetterInside a @property getter or setter named 'price', reading or assigning 'self.price' instead of the backing attribute 'self._price' calls the property getter/setter recursively until stack overflow.Store the underlying data on a private backing attribute prefixed with an underscore (self._price) inside the @property methods.
Mid-LevelGenerator Exhaustion Bug (Silent Empty Second Iteration)Generators and iterators (including map(), filter(), zip()) are single-pass streams. Once iterated over (e.g., via sum(gen) or list(gen)), the generator is permanently exhausted and any subsequent loop yields 0 items without raising an error.Convert to a tuple/list if you need multiple passes over small data, or pass a callable factory / re-invoke the generator function for each pass.
Mid-LevelRuntimeError: generator didn't stop after throw() / didn't yieldIn a @contextlib.contextmanager function, if the code inside the 'with' block raises an exception and your generator catches it without re-raising OR yields a second time, contextlib raises RuntimeError.Wrap the single 'yield' inside a 'try:... finally:...' block in @contextmanager so cleanup always runs and exceptions propagate naturally.
Mid-LevelDecorator Metadata Loss (Missing @functools.wraps)Writing a decorator wrapper without @functools.wraps(func) overwrites the original function's __name__, __doc__, and __annotations__ with 'wrapper', breaking FastAPI route inspection, Sphinx docs, and pytest fixtures.Always decorate inner wrapper functions with @functools.wraps(func).
Mid-LevelImportError: cannot import name '...' from partially initialized module (Circular Import)Module A imports Module B at top-level while Module B also imports Module A at top-level. Whichever module is imported second sees the first module before it has finished executing its top-level class/function definitions.Extract shared models/interfaces into a third base module (e.g., schemas.py or protocols.py), or use 'from __future__ import annotations' with 'if TYPE_CHECKING:' for type-only imports.
Mid-Leveljson.decoder.JSONDecodeError / TypeError: Object of type datetime is not JSON serializablejson.loads() fails with JSONDecodeError on empty strings, single quotes, or trailing commas; json.dumps() fails with TypeError on datetime, UUID, Decimal, or custom objects.Validate non-empty payloads before json.loads(), and pass default=str (or a custom encoder / Pydantic .model_dump_json()) to json.dumps().
Mid-LevelLost Exception Context (Raising Without 'from err')Catching a low-level exception and raising a custom domain exception via 'raise ServiceError(...)' without chaining hides the original traceback root cause.Always use 'raise DomainError(...) from err' to preserve the cause chain in __cause__.
πŸ“š Complete Mid-Level Python Curriculum Reference (26 Core Engineering Topics)

This interactive Mid-Level Python Systems Studio covers 26 production engineering modules across 4 specialized tracks:

  • Track 01 β€” Functions, Closures & Decorators (Topics 1–12): Argument unpacking (*args, **kwargs), positional-only and keyword-only parameters, first-class functions, lexical closures, functools.wraps decorators, parameterized decorators, lru_cache memoization, generator functions (yield), generator expressions, itertools pipelines, lambda expressions, and functools.partial.
  • Track 02 β€” Object-Oriented Design, Dataclasses & Typing (Topics 13–20): Immutable @dataclass(frozen=True) and field(default_factory=...), @property getters and validation setters, @classmethod and @staticmethod factories, Abstract Base Classes (abc.ABC), structural subtyping with typing.Protocol, Method Resolution Order (C3 Linearization & super()), magic dunder methods (__repr__, __eq__, __lt__), and Generic type variables (TypeVar, Generic[T]).
  • Track 03 β€” CPython Memory Model, Namespaces & References (Topics 21–25): Namespaces and the LEGB scope resolution rule (Local, Enclosing, Global, Built-in), mutable vs. immutable object identity, shallow copy vs. deep copy semantics (copy.deepcopy), CPython PyObject headers and reference counting (sys.getrefcount), and cyclic garbage collection with weak references (gc, weakref).
  • Track 04 β€” Exception Architecture & Context Managers (Topic 26): Designing domain-specific custom exception hierarchies, explicit exception chaining (raise CustomError from exc), and deterministic resource cleanup with custom context managers (__enter__ / __exit__ and @contextlib.contextmanager).
⚑ 30-Second Developer Summary

Production Error Management Principles

  • Preserve Traceback Context: Explicit exception chaining (`raise CustomError(...) from e`) populates `__cause__`, retaining low-level error stack traces without leaking implementation details to API callers.
  • Domain-Specific Hierarchy: Inherit all application exceptions from a base `AppError(Exception)` to allow callers to catch high-level domain failures cleanly.

1. Designing Custom Exception Hierarchies

A well-designed exception hierarchy groups errors by domain, enabling callers to selectively catch coarse or fine-grained exceptions.

class ApplicationError(Exception):
    """Base exception for all application errors."""
    pass

class DatabaseConnectionError(ApplicationError):
    """Raised when database host fails to respond."""
    pass

class DataValidationError(ApplicationError):
    """Raised when inbound JSON payload violates domain constraints."""
    pass

try:
    raise DataValidationError("Field 'email' is required.")
except ApplicationError as err:
    print(f"Caught Application Level Error: {type(err).__name__} -> {err}")

2. Explicit Exception Chaining (`raise ... from ...`)

Use `raise HighLevelError(...) from low_level_err` to transform technical errors into user-friendly domain errors while preserving original debugging context in `__cause__`.

import json

def parse_user_config(raw_json: str) -> dict:
    try:
        return json.loads(raw_json)
    except json.JSONDecodeError as err:
        # Explicitly chain JSONDecodeError into DataValidationError
        raise DataValidationError("Failed to parse configuration JSON payload") from err

try:
    parse_user_config("invalid_json_str{")
except DataValidationError as exc:
    print("Handled Exception:", exc)
    print("Underlying Root Cause:", repr(exc.__cause__))

3. Exception Groups & `except*` (Python 3.11+)

Python 3.11 introduced `ExceptionGroup` and `except*` to handle multiple concurrent failures simultaneously (e.g. parallel asyncio tasks or batch operations).

# Python 3.11+ Exception Group Example
eg = ExceptionGroup(
    "Batch Task Failures",
    [
        ValueError("Invalid User ID"),
        TypeError("Expected string, got int"),
        KeyError("Missing 'auth_token' key")
    ]
)

try:
    raise eg
except* ValueError as eg_val:
    print("Handled ValueErrors:", eg_val.exceptions)
except* (TypeError, KeyError) as eg_type:
    print("Handled Type & Key Errors:", eg_type.exceptions)

⭐ Rate Track 04: Advanced Exception Architecture (1 to 5 Stars)

Your rating is stored directly in the database. Average: 4.9 / 5 (1 rating)

β˜… β˜… β˜… β˜… β˜…
← Track 03: Memory & Object Model Return to Mid-Level Hub β†’