12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

• However, there are exceptions to the prior rule—in a simple script, you maywant failures of such operations to kill your program instead of being caught andignored. This is especially true if the failure is a showstopper. Failures in <strong>Python</strong>result in useful error messages (not hard crashes), and this is often the best outcomeyou could hope for.• You should implement termination actions in try/finally statements to guaranteetheir execution. This statement form allows you to run code whether exceptionsoccur or not.• It is sometimes more convenient to wrap the call to a large function in a singletry statement, rather than littering the function itself with many try statements.That way, all exceptions in the function percolate up to the try around the call,and you reduce the amount of code within the function.The types of programs you write will probably influence the amount of exceptionhandling you code as well. Servers, for instance, must generally keep running persistently,and so will likely require try statements to catch and recover from exceptions.In-process testing programs of the kind we saw in this chapter will probablyhandle exceptions as well. Simpler one-shot scripts, though, will often ignore exceptionhandling completely because failure at any step requires script shutdown.Catching Too Much: Avoid Empty exceptsOn to the issue of handler generality. <strong>Python</strong> lets you pick and choose which exceptionsto catch, but you sometimes have to be careful to not be too inclusive. Forexample, you’ve seen that an empty except clause catches every exception that mightbe raised while the code in the try block runs.That’s easy to code, and sometimes desirable, but you may also wind up interceptingan error that’s expected by a try handler higher up in the exception nesting structure.For example, an exception handler such as the following catches and stops everyexception that reaches it, regardless of whether another handler is waiting for it:def func( ):try:... # IndexError is raised in hereexcept:... # But everything comes here and dies!try:func( )except IndexError:...# Exception should be processed herePerhaps worse, such code might also catch unrelated system exceptions. Even thingslike memory errors, genuine programming mistakes, iteration stops, and system exitsraise exceptions in <strong>Python</strong>. Such exceptions should not usually be intercepted.Exception Design Tips | 625

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

Saved successfully!

Ooh no, something went wrong!