Python Glossary Русский

all Python 3Exceptionsexception

GeneratorExit

built-in exceptions

Raised inside a generator when it is closed (.close()). Inherits BaseException.

Syntax

raise GeneratorExit

It inherits from BaseException rather than Exception on purpose: a plain except Exception inside the generator will not swallow it and cannot block the shutdown. It surfaces at the yield where the generator is suspended, triggered by .close() or by garbage collection of the generator object. You rarely need to catch it — try/finally is enough for cleanup — and if the generator yields again after catching it, the interpreter raises RuntimeError about an ignored GeneratorExit.

Examples

try:
    raise GeneratorExit
except GeneratorExit as e:
    print(type(e).__name__)   # → GeneratorExit

See also

Open in the full glossarydocs.python.orgReport an inaccuracy