[ Team LiB ] |
25.1 String-Based ExceptionsIn 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. |
[ Team LiB ] |