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.

But this workaround might catch more than they bargained for—even things likevariable name typos, memory errors, and system exits trigger exceptions, and youwant such things to pass, not be caught and erroneously classified as library errors.As a rule of thumb, it’s usually better to be specific than general in exception handlers(an idea we’ll revisit in the gotchas section in the next chapter). *So what to do, then? Class exceptions fix this dilemma completely. Rather thandefining your library’s exceptions as a simple set of strings, arrange them into a classtree with a common superclass to encompass the entire category:# mathlib.pyclass NumErr(Exception): passclass Divzero(NumErr): passclass Oflow(NumErr): pass...def func( ):...raise DivZero( )This way, users of your library simply need to list the common superclass (i.e., category)to catch all of your library’s exceptions, both now and in the future:# client.pyimport mathlib...try:mathlib.func(...)except mathlib.NumErr:...report and recover...When you go back and hack your code again, new exceptions are added as new subclassesof the common superclass:# mathlib.py...class Uflow(NumErr): passThe end result is that user code that catches your library’s exceptions will keep working,unchanged. In fact, you are free to add, delete, and change exceptions arbitrarilyin the future—as long as clients name the superclass, they are insulated from changesin your exceptions set. In other words, class exceptions provide a better answer to* As a clever student of mine suggested, the library module could also provide a tuple object that contains allthe exceptions the library can possibly raise—the client could then import the tuple and name it in an exceptclause to catch all the library’s exceptions (recall that a tuple in an except means catch any of its exceptions).When a new exception is added later, the library can just expand the exported tuple. This works, but you’dstill need to keep the tuple up-to-date with raised exceptions inside the library module. Also, class-basedexceptions offer more benefits than just categories—they also support attached state information, methodcalls, and inheritance, which simple string exceptions do not.608 | Chapter 28: Exception Objects

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

Saved successfully!

Ooh no, something went wrong!