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.

ChapterCHAPTER2828Exception Objects 28So far, I’ve been deliberately vague about what an exception actually is. <strong>Python</strong> generalizesthe notion of exceptions—as mentioned in the prior chapter, they may beidentified by string objects or class instance objects; class instance objects are preferredtoday, and will be required soon. Both approaches have merits, but classestend to provide a better solution when it comes to maintaining exception hierarchies.In short, class-based exceptions allow us to build exceptions that are organized intocategories, have attached state information, and support inheritance. In more detail,compared to the older string exception model, class exceptions:• Better support future changes by providing categories—adding new exceptionsin the future won’t generally require changes in try statements.• Provide a natural place for us to store context information for use in the try handler—theymay have both attached state information and callable methods,accessible through instances.• Allow exceptions to participate in inheritance hierarchies to obtain commonbehavior—inherited display methods, for example, can provide a common lookand feel for error messages.Because of these differences, class-based exceptions support program evolution andlarger systems better than string-based exceptions. String exceptions may seem easierto use at first glance, when programs are small, but they can become more difficultwhen programs grow large. In fact, all built-in exceptions are identified by classes,and are organized into an inheritance tree, for the reasons just listed. You can do thesame with user-defined exceptions.In the interest of backward compatibility, I’ll present both string and class-basedexceptions here. Both currently work, but string exceptions generate deprecationwarnings in the current release of <strong>Python</strong> (2.5), and will no longer be supported at allin <strong>Python</strong> 3.0. We’ll cover them here because they are likely to appear in existingcode you encounter, but new exceptions you define should be coded as classestoday, partly because classes are better, but also because you probably won’t want tochange your exception code when <strong>Python</strong> 3.0 is rolled out.602

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

Saved successfully!

Ooh no, something went wrong!