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.

B RAINB UILDERChapter Quiz1. How are raised string-based exceptions matched to handlers?2. How are raised class-based exceptions matched to handlers?3. How can you attach context information to class-based exceptions, and use it inhandlers?4. How can you specify the error message text in class-based exceptions?5. Why should you not use string-based exceptions anymore today?Quiz Answers1. String-based exceptions match by object identity (technically, via the is expression),not by object value (the == expression). Hence, naming the same stringvalue might not work; you need to name the same object reference (usually avariable). Short strings are cached and reused in <strong>Python</strong>, so naming the samevalue might work occasionally, but you can’t rely on this (more on this in a“gotcha” at the end of the next chapter).2. Class-based exceptions match by superclass relationships: naming a superclassin an exception handler will catch instances of that class, as well as instances ofany of its subclasses lower in the class tree. Because of this, you can think ofsuperclasses as general exception categories, and subclasses as more specificexception types within those categories.3. You attach context information to class-based exceptions by filling out instanceattributes in the instance object raised, often in class constructor methods. Inexception handlers, you list a variable to be assigned to the raised instance, thengo through this name to access attached state information, and call any inheritedclass methods.4. The error message text in class-based exceptions can be specified with the _ _repr_ _or _ _str_ _ operator overloading methods. If you inherit from the built-in Exceptionclass, anything you pass to the class constructor is displayed automatically.5. Because Guido said so—they are scheduled to go away in a future <strong>Python</strong>release. Really, there are good reasons for this: string-based exceptions do notsupport categories, state information, or behavior inheritance in the way classbasedexceptions do. In practice, this makes string-based exceptions easier to useat first, when programs are small, but more complex to use as programs growlarger.616 | Chapter 28: Exception Objects

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

Saved successfully!

Ooh no, something went wrong!