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. ...

Get Learning Python, 2nd 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.