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.
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">>>
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
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
raise myexcTraceback (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.
Strings are a simple way to define your exceptions. Exceptions may also be identified with classes. ...