Chapter 6. Exceptions

Python uses exceptions to indicate errors and anomalies. When Python detects an error, it raises an exception—that is, Python signals the occurrence of an anomalous condition by passing an exception object to the exception propagation mechanism. Your code can explicitly raise an exception by executing a raise statement.

Handling an exception means catching the exception object from the propagation mechanism and taking actions as needed to deal with the anomalous situation. If a program does not handle an exception, the program terminates with an error message and traceback message. However, a program can handle exceptions and keep running, despite errors or other anomalies, by using the try statement with except clauses.

Python also uses exceptions to indicate some situations that are not errors, and not even abnormal. For example, as covered in “Iterators”, calling the next built-in function on an iterator raises StopIteration when the iterator has no more items. This is not an error; it is not even an anomaly, since most iterators run out of items eventually. The optimal strategies for checking and handling errors and other special situations in Python are therefore different from those in other languages; we cover them in “Error-Checking Strategies”.

This chapter shows how to use exceptions for errors and special situations. It also covers the logging module of the standard library, in “Logging Errors”, and the assert statement, in “The assert Statement” ...

Get Python in a Nutshell, 4th Edition 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.