GeneratorExit

GeneratorExit is a built-in exception that occurs when a generator or coroutine is closed.

You usually won’t catch this exception directly. Instead, you’ll handle it implicitly by making sure your generator releases any resources or performs any needed cleanup before it finishes.

GeneratorExit Occurs When

  • Calling the .close() method on a generator or coroutine
  • Python raises GeneratorExit inside the generator or coroutine so it can perform final cleanup tasks

GeneratorExit Can Be Used When

  • Closing a generator and ensuring it performs any required cleanup
  • Writing custom generators that handle resource management
  • Working with coroutines that need cleanup before termination

Example

An example of a generator that prints a closing message when it’s stopped:

Python
>>> def count_up(max_value):
...     try:
...         count = 1
...         while count <= max_value:
...             yield count
...             count += 1
...     except GeneratorExit:
...         print("Generator is closing...")
...

>>> counter = count_up(5)
>>> print(next(counter))
1
>>> counter.close()
Generator is closing...

Although you usually won’t raise GeneratorExit manually, it’s automatically raised when you call a generator’s .close() method.

Tutorial

How to Use Generators and yield in Python

In this step-by-step tutorial, you'll learn about generators and yielding in Python. You'll create generator functions and generator expressions using multiple Python yield statements. You'll also learn how to build data pipelines that take advantage of these Pythonic tools.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated March 17, 2025 • Reviewed by Martin Breuss