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.

finally runfinally runTraceback (most recent call last):File "C:/<strong>Python</strong>25/except-finally.py", line 9, in func( )File "C:/<strong>Python</strong>25/except-finally.py", line 3, in raise2def raise2( ): raise SyntaxErrorSyntaxError: NoneAs we saw in Chapter 27, as of <strong>Python</strong> 2.5, except and finally clauses can be mixedin the same try statement. This makes some of the syntactic nesting described in thissection unnecessary, though it still works, may appear in code written prior to<strong>Python</strong> 2.5, and can be used as a technique for implementing alternative exceptionhandlingbehaviors.Exception IdiomsWe’ve seen the mechanics behind exceptions. Now, let’s take a look at some of theother ways they are typically used.Exceptions Aren’t Always ErrorsIn <strong>Python</strong>, all errors are exceptions, but not all exceptions are errors. For instance,we saw in Chapter 9 that file object read methods return an empty string at the end ofa file. In contrast, the built-in raw_input function (which we first met in Chapter 3, anddeployed in an interactive loop in Chapter 10) reads a line of text from the standardinput stream, sys.stdin, at each call, and raises the built-in EOFError at end-of-file.Unlike file methods, this function does not return an empty string—an empty stringfrom raw_input means an empty line. Despite its name, the EOFError exception is just asignal in this context, not an error. Because of this behavior, unless end-of-file shouldterminate a script, raw_input often appears wrapped in a try handler and nested in aloop, as in the following code:while 1:try:line = raw_input( ) # Read line from stdinexcept EOFError:break# Exit loop at end-of-fileelse:...process next line here...Other built-in exceptions are similarly signals, not errors. <strong>Python</strong> also has a set of builtinexceptions that represent warnings rather than errors. Some of these are used to signaluse of deprecated (phased out) language features. See the standard library manual’sdescription of built-in exceptions, and the warnings module for more on warnings.Exception Idioms | 621

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

Saved successfully!

Ooh no, something went wrong!