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.

At the end of this chapter, we’ll also meet some more complete testing frameworksprovided by <strong>Python</strong>, such as Doctest and PyUnit, which provide tools for comparingexpected outputs with actual results.More on sys.exc_infoThe sys.exc_info result used in the last two sections is the preferred way to gainaccess to the most recently raised exception generically. If no exception is being handled,it returns a tuple containing three None values; otherwise, the values returnedare (type, value, traceback), where:• type is the exception type of the exception being handled (a class object forclass-based exceptions).• value is the exception parameter (its associated value or the second argument toraise, which is always a class instance if the exception type is a class object).• traceback is a traceback object that represents the call stack at the point wherethe exception originally occurred (see the standard traceback module’s documentationfor tools that may be used in conjunction with this object to generateerror messages manually).The older tools sys.exc_type and sys.exc_value still work to fetch the most recentexception type and value, but they can manage only a single, global exception for theentire process. The preferred sys.exc_info instead keeps track of each thread’sexception information, and so is thread-specific. Of course, this distinction mattersonly when using multiple threads in <strong>Python</strong> programs (a subject beyond this book’sscope). See the <strong>Python</strong> library manual or follow-up texts for more details.Exception Design TipsBy and large, exceptions are easy to use in <strong>Python</strong>. The real art behind them is indeciding how specific or general your except clauses should be, and how much codeto wrap up in try statements. Let’s address the second of these concerns first.What Should Be WrappedIn principle, you could wrap every statement in your script in its own try, but thatwould just be silly (the try statements would then need to be wrapped in try statements!).This is really a design issue that goes beyond the language itself, andbecomes more apparent with use. But here are a few rules of thumb:• Operations that commonly fail should generally be wrapped in try statements.For example, operations that interface with system state (file opens, socket calls,and the like) are prime candidates for trys.624 | Chapter 29: Designing with Exceptions

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

Saved successfully!

Ooh no, something went wrong!