12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

String-Based ExceptionsIn all the examples we’ve seen up to this point, user-defined exceptions have beencoded as strings. This is the simpler way to code an exception. For example:>>> myexc = "My exception string">>> try:... raise myexc... except myexc:... print 'caught'...caughtAny string value can be used to identify an exception. Technically, the exception isidentified by the string object, not the string value—you must use the same variable(i.e., reference) to raise and catch the exception (I’ll expand on this idea in a gotchaat the conclusion of Part VII). Here, the exception name, myexc, is just a normal variable—itcan be imported from a module, and so on. The text of the string is almostirrelevant, except that it is printed as the exception message:>>> raise myexcTraceback (most recent call last):File "", line 1, in ?My exception stringIf your string exceptions may print like this, you’ll want to use moremeaningful text than most of the examples shown in this book.String Exceptions Are Right Out!As mentioned earlier, string-based exceptions still work, but they generate warnings asof <strong>Python</strong> 2.5, and are scheduled to go away completely in <strong>Python</strong> 3.0, if not earlier. Infact, here is the real output of the preceding code when run in IDLE under <strong>Python</strong> 2.5:>>> myexc = 'My exception string'>>> try:raise myexcexcept myexc:print 'caught'Warning (from warnings module):File "_ _main_ _", line 2DeprecationWarning: raising a string exception is deprecatedcaughtYou can disable such warnings, but they are generated to let you know that stringexceptions will become errors in the future, and thus will be completely disallowed.This book’s coverage of string exceptions is retained just to help you understandcode written in the past; today, all built-in exceptions are class instances, and alluser-defined exceptions you create should be class-based as well. The next sectionexplains why.String-Based Exceptions | 603

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!