Skip to Content
Learning Python, 2nd Edition
book

Learning Python, 2nd Edition

by Mark Lutz, David Ascher
December 2003
Beginner
620 pages
17h 3m
English
O'Reilly Media, Inc.
Content preview from Learning Python, 2nd Edition

Chapter 25. Exception Objects

So far, we’ve been deliberately vague about what an exception actually is. Python generalizes the notion of exceptions—they may be identified by either string or class objects. Both have merits, but classes tend to provide a better solution when it comes to maintaining exception hierarchies.

String-Based Exceptions

In all the examples we’ve seen up to this point, user-defined exceptions have been strings. This is the simpler way to code an exception—any string value can be used to identify an exception:

>>> myexc = "My exception string"
>>> try:
...     raise myexc
... except myexc:
...     print 'caught'
...
caught

Technically, the exception is identified by the string object, not the string value—you must use the same variable (i.e., reference) to raise and catch the exception (we’ll expand on this idea in a gotcha at the conclusion of Part VII). Here, the exception name myexc is just a normal variable—it can be imported from a module, and so on. The text of the string is almost irrelevant, except that it shows up in standard error messages:

>>> raise myexc
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
My exception string

The text of the string exception here is printed as the exception message. If your string exceptions may print like this, you’ll want to use more meaningful text than most of the examples shown in this book.

Class-Based Exceptions

Strings are a simple way to define your exceptions. Exceptions may also be identified with classes. ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Python, 5th Edition

Learning Python, 5th Edition

Mark Lutz

Publisher Resources

ISBN: 0596002815Supplemental ContentErrata Page