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:
>>> 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.
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Python Exceptions: An Introduction (Tutorial)
- Python's raise: Effectively Raising Exceptions in Your Code (Tutorial)
- Python Generators 101 (Course)
- How to Use Generators and yield in Python (Quiz)
- Introduction to Python Exceptions (Course)
- Raising and Handling Python Exceptions (Course)
- Python Exceptions: An Introduction (Quiz)
- Using raise for Effective Exceptions (Course)
- Python's raise: Effectively Raising Exceptions in Your Code (Quiz)