raise — Advanced Examples
Throws an exception manually
Raise in context managers and generators
Exception interaction with advanced patterns.
python
from contextlib import contextmanager @contextmanager def must_not_fail(label): try: yield except Exception as e: raise RuntimeError(f"{label} failed") from e try: with must_not_fail("data load"): raise ValueError("bad data") except RuntimeError as e: print(f"Caught: {e}") print(f"Original: {e.__cause__}") # Raise in a generator def safe_divide_gen(pairs): for a, b in pairs: try: yield a / b except ZeroDivisionError: yield float("inf") results = list(safe_divide_gen([(10, 2), (5, 0), (9, 3)])) print(results)
Expected Output
Caught: data load failed Original: bad data [5.0, inf, 3.0]
Exceptions raised inside context managers and generators interact with their surrounding protocol (__exit__ and throw()).
Want to try these examples interactively?
Open Advanced Playground