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.

the globals reside in. Passing extra data along with the exception itself enables thetry statement to access it more reliably. Strictly speaking, every exception has thisextra data: as with function return values, it defaults to the special None object ifnothing is passed explicitly. The following code, raisedata.py, illustrates this conceptat work with simple string-based exceptions:myException = 'Error'def raiser1( ):raise myException, "hello"def raiser2( ):raise myExceptiondef tryer(func):try:func( )except myException, extraInfo:print 'got this:', extraInfo# String object# Raise, pass data# Raise, None implied# Run func; catch exception + data% python>>> from raisedata import *>>> tryer(raiser1) # Explicitly passed extra datagot this: hello>>> tryer(raiser2) # Extra data is None by defaultgot this: NoneHere, the tryer function always requests the extra data object; it comes back as anexplicit string from raiser1, but defaults to None in raiser2’s raise statement.In the next chapter, we’ll see that the same hook can also be used to access instancesraised in conjunction with class-based exceptions—the variable in the except is thenassigned to the raised instance, which gives access to attached state information, aswell as callable class methods.Example: Propagating Exceptions with raiseA raise statement that does not include an exception name or extra data value simplyreraises the current exception. This form is typically used if you need to catchand handle an exception, but don’t want the exception to die in your code:>>> try:... raise IndexError, 'spam'... except IndexError:... print 'propagating'... raise...propagatingTraceback (most recent call last):File "", line 2, in ?IndexError: spam594 | Chapter 27: Exception Basics

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

Saved successfully!

Ooh no, something went wrong!