Use cases for exceptions

The use cases for exceptions are very broad. We'll identify a few significant areas where exceptions are used in Python.

Some exceptions are entirely benign. The StopIteration exception is raised by an iterable that has run out of values. The for statement consumes items from the iterable until this exception is raised to signal that there's no more data. Similarly, a GeneratorExit is used when a generator is closed before producing all of its data. This is not an error; it's a signal that more data will not be requested.

Conditions that are entirely outside the program may be seen as exceptions. Unexpected OS conditions or errors are signaled by exceptions which are subclasses of the OSError exception. Some OS conditions ...

Get Python Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.