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.

As a rule of thumb, be as specific in your handlers as you can be—empty exceptclauses are handy, but potentially error-prone. In the last example, for instance, youwould be better off saying except KeyError: to make your intentions explicit andavoid intercepting unrelated events. In simpler scripts, the potential for problemsmight not be significant enough to outweigh the convenience of a catchall, but ingeneral, general handlers are generally trouble.Catching Too Little: Use Class-Based CategoriesOn the other hand, neither should handlers be too specific. When you list specificexceptions in a try, you catch only what you actually list. This isn’t necessarily a badthing, but if a system evolves to raise other exceptions in the future, you may need togo back and add them to exception lists elsewhere in your code.For instance, the following handler is written to treat myerror1 and myerror2 as normalcases, and treat everything else as an error. If a myerror3 is added in the future, itis processed as an error, unless you update the exception list:try:...except (myerror1, myerror2): # Breaks if I add a myerror3... # Nonerrorselse:... # Assumed to be an errorLuckily, careful use of the class-based exceptions we discussed in Chapter 28 can makethis trap go away completely. As we saw, if you catch a general superclass, you can addand raise more specific subclasses in the future without having to extend except clauselists manually—the superclass becomes an extendible exceptions category:try:...except SuccessCategoryName: # OK if I add a myerror3 subclass... # Nonerrorselse:... # Assumed to be an errorWhether you use class-based exception category hierarchies, a little design goes along way. The moral of the story is to be careful to not be too general or too specificin exception handlers, and to pick the granularity of your try statement wrappingswisely. Especially in larger systems, exception policies should be a part of the overalldesign.Exception GotchasThere isn’t much to trip over with exceptions, but here are two general usage pointers(one of which summarizes concepts we’ve already met).Exception Gotchas | 627

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

Saved successfully!

Ooh no, something went wrong!