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.

uns the statements under the first one that matches. If none match, the exception ispropagated past this try. Note that the else runs only when no exception occurs inaction—it does not run when an exception without a matching except is raised.If you really want a general “catch-all” clause, an empty except does the trick:try:action( )except NameError:... # Handle NameErrorexcept IndexError:... # Handle IndexErrorexcept:... # Handle all other exceptionselse:... # Handle the no-exception caseThe empty except clause is a sort of wildcard feature—because it catches everything,it allows your handlers to be as general or specific as you like. In some scenarios, thisform may be more convenient than listing all possible exceptions in a try. For example,the following catches everything without listing anything:try:action( )except:... # Catch all possible exceptionsEmpty excepts also raise some design issues, though. Although convenient, they maycatch unexpected system exceptions unrelated to your code, and may inadvertentlyintercept exceptions meant for another handler. For example, even system exit callsin <strong>Python</strong> trigger exceptions, and you usually want these to pass. We’ll revisit this asa gotcha at the end of this part of the book. For now, I’ll just say: use with care.In <strong>Python</strong> 3.0, the third row of Table 27-1 is scheduled to change:except name, value: will instead be coded as except name as value:.This change is being made to remove syntax confusion when a tuple ofalternative exceptions is coded—the fourth row in Table 21-1 will nolonger require enclosing parentheses in 3.0. This change will alsomodify the scoping rules: with the new as syntax, the value variable atthe end of the except block will be deleted.Also in 3.0, the raise statement form raise E, V will need to be codedas raise E(V) to explicitly generate a class instance to be raised. Theprior form had been retained just for backward compatibility withstring exceptions in <strong>Python</strong> 2.x. (See later in this chapter for more onraise, and the next chapter for a discussion of class-based exceptions.)Although you can’t use the as form of except in <strong>Python</strong> 2.x to futureproofyour code, the “2to3” conversion tool to be shipped with 3.0will automate the except and raise translations for existing 2.x code.584 | Chapter 27: Exception Basics

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

Saved successfully!

Ooh no, something went wrong!