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.

Functions Signal Conditions with raiseUser-defined exceptions can also signal nonerror conditions. For instance, a searchroutine can be coded to raise an exception when a match is found, instead of returninga status flag for the caller to interpret. In the following, the try/except/elseexception handler does the work of an if/else return-value tester:class Found(Exception): passdef searcher( ):if ...success...:raise Found( )else:returntry:searcher( )except Found:...success...else:...failure...# Exception if item was found# else returned: not foundMore generally, such a coding structure may also be useful for any function that cannotreturn a sentinel value to designate success or failure. For instance, if all objectsare potentially valid return values, it’s impossible for any return value to signalunusual conditions. Exceptions provide a way to signal results without a returnvalue:class Failure(Exception): passdef searcher( ):if ...success...:return ...founditem...else:raise Failure( )try:item = searcher( )except Failure:...report...else:...use item here...Because <strong>Python</strong> is dynamically typed and polymorphic to the core, exceptions, ratherthan sentinel return values, are the generally preferred way to signal such conditions.Debugging with Outer try StatementsYou can also make use of exception handlers to replace <strong>Python</strong>’s default top-levelexception-handling behavior. By wrapping an entire program (or a call to it) in anouter try in your top-level code, you can catch any exception that may occur whileyour program runs, thereby subverting the default program termination.622 | Chapter 29: Designing with Exceptions

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

Saved successfully!

Ooh no, something went wrong!