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.

For example, scripts normally exit when control falls off the end of the top-level file.However, <strong>Python</strong> also provides a built-in sys.exit(statuscode) call to allow earlyterminations. This actually works by raising a built-in SystemExit exception to endthe program, so that try/finally handlers run on the way out, and special types ofprograms can intercept the event. * Because of this, a try with an empty except mightunknowingly prevent a crucial exit, as in the following file (exiter.py):import sysdef bye( ):sys.exit(40)try:bye( )except:print 'got it'print 'continuing...'# Crucial error: abort now!# Oops—we ignored the exit% python exiter.pygot itcontinuing...You simply might not expect all the kinds of exceptions that could occur during anoperation.Probably worst of all, an empty except will also catch genuine programming errors,which should be allowed to pass most of the time. In fact, empty except clauses caneffectively turn off <strong>Python</strong>’s error-reporting machinery, making it difficult to noticemistakes in your code. Consider this code, for example:mydictionary = {...}...try:x = myditctionary['spam']except:x = None...continue here with x...# Oops: misspelled# Assume we got KeyErrorThe coder here assumes that the only sort of error that can happen when indexing adictionary is a missing key error. But because the name myditctionary is misspelled(it should say mydictionary), <strong>Python</strong> raises a NameError instead for the undefinedname reference, which the handler will silently catch and ignore. The event handlerwill incorrectly fill in a default for the dictionary access, masking the program error.If this happens in code that is far removed from the place where the fetched valuesare used, it might make for a very interesting debugging task!* A related call, os._exit, also ends a program, but via an immediate termination—it skips cleanup actions,and cannot be intercepted with try/except or try/finally blocks. It is usually only used in spawned childprocesses, a topic beyond this book’s scope. See the library manual or follow-up texts for details.626 | Chapter 29: Designing with Exceptions

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

Saved successfully!

Ooh no, something went wrong!