Chapter 34. Exception Coding Details
In the prior chapter we took a quick look at exception-related statements in action. Here,
we’re going to dig a bit deeper—this chapter provides a more formal
introduction to exception processing syntax in Python. Specifically, we’ll
explore the details behind the try
,
raise
, assert
, and with
statements. As we’ll see, although these
statements are mostly straightforward, they offer powerful tools for dealing
with exceptional conditions in Python code.
Note
One procedural note up front: The exception story has changed in
major ways in recent years. As of Python 2.5, the finally
clause can appear in the same try
statement as except
and else
clauses (previously, they could not be
combined). Also, as of Python 3.0 and 2.6, the new with
context manager statement has become
official, and user-defined exceptions must now be coded as class
instances, which should inherit from a built-in exception superclass.
Moreover, 3.X sports slightly modified syntax for the raise
statement and except
clauses, some of which is available in
2.6 and 2.7.
I will focus on the state of exceptions in recent Python 2.X and 3.X releases in this edition, but because you are still very likely to see the original techniques in code for some time to come, along the way I’ll point out how things have evolved in this domain.
The try/except/else Statement
Now that we’ve seen the basics, it’s time for the details. In the following
discussion, I’ll first present try
/except
/else
and try ...
Get Learning Python, 5th 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.