GeneratorExit — Easy Examples
Raised when a generator's close() method is called
Triggering GeneratorExit
How GeneratorExit is raised and how to catch it.
python
# Triggering and catching GeneratorExit try: raise GeneratorExit("generator closed") except GeneratorExit as e: print(f"Caught GeneratorExit: {e}") print(f"Type: {type(e).__name__}")
GeneratorExit is raised when raised when a generator's close() method is called. Always catch specific exceptions rather than bare except clauses.
Handling GeneratorExit
Basic error handling pattern for GeneratorExit.
python
# Safe handling pattern def safe_operation(): try: raise GeneratorExit("generator closed") except GeneratorExit: print("Operation failed gracefully") return None result = safe_operation() print(f"Result: {result}")
Wrapping risky operations in try/except blocks prevents your program from crashing.
Want to try these examples interactively?
Open Easy Playground