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.

So, what’s an exception name? It might be the name of a built-in exception from thebuilt-in scope (e.g., IndexError), or the name of an arbitrary string object you’veassigned in your program. It can also reference a user-defined class, or classinstance—a possibility that further generalizes raise statement formats. I’ll postponethe details of this generalization until after we’ve had a chance to study classexceptions in the next chapter.Regardless of how you name exceptions, they are always identified by normalobjects, and at most one is active at any given time. Once caught by an except clauseanywhere in the program, an exception dies (i.e., won’t propagate to another try),unless it’s reraised by another raise statement or error.Example: Raising and Catching User-Defined Exceptions<strong>Python</strong> programs can trigger built-in and user-defined exceptions using the raisestatement. User-defined exceptions should be class instance objects today, like theone that calling MyBad creates in the following code:class MyBad: passdef stuff( ):raise MyBad( )# Trigger exception manuallytry:stuff( )# Raises exceptionexcept MyBad:print 'got it'# Handle exception here... # Resume execution hereThis time the raise occurs inside a function, but this makes no real difference—control jumps back to the except block immediately. Notice that user-definedexceptions are caught with try statements, just like built-in exceptions.Example: Passing Extra Data with raiseAs stated earlier, a raise statement can pass an extra data item along with the exceptionfor use in a handler. In general, the extra data allows you to send context informationabout the exception to a handler. If you’re writing a data file parser, for example, youmight raise a syntax error exception on errors and also pass along an object that givesline and file information to the handler (we’ll meet such an example in Chapter 28).This is useful because when an exception is raised, it may cross arbitrary file boundaries—theraise statement that triggers an exception, and the try statement thatcatches it may be in completely different files. It is not generally feasible to storeextra details in global variables because the try statement might not know which fileThe raise Statement | 593

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

Saved successfully!

Ooh no, something went wrong!