Chapter 27. Exception Basics

This last part of the book deals with exceptions, which are events that can modify the flow of control through a program. In Python, exceptions are triggered automatically on errors, and can be triggered and intercepted by your code. They are processed by four statements we’ll study in this part, the first of which has two variations (listed separately here), and the last of which is an optional extension until Python 2.6:


Catch and recover from exceptions raised by Python, or by you.


Perform cleanup actions, whether exceptions occur or not.


Trigger an exception manually in your code.


Conditionally trigger an exception in your code.


Implement context managers in Python 2.6 and later (optional in 2.5).

This topic was saved for this last part of the book because you need to know about classes to code exceptions of your own. With a few exceptions (pun intended), though, you’ll find that exception handling is simple in Python because it’s integrated into the language itself as another high-level tool.

One procedural note up front: the exception story has changed in two major ways since this book was first written—the finally clause can now appear in the same try statement as except and else clauses, and user-defined exceptions should now be coded as class instances not strings. I will describe both the old and new ways of doing things in this edition, because you are still very likely to see the original techniques in ...

Get Learning Python, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.