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.

def raiser1( ):X = Specific1( )raise Xdef raiser2( ):X = Specific2( )raise X# Raise subclass instance# Raise different subclass instancefor func in (raiser0, raiser1, raiser2):try:func( )except General: # Match General or any subclass of itimport sysprint 'caught:', sys.exc_info( )[0]C:\python> python classexc.pycaught: _ _main_ _.Generalcaught: _ _main_ _.Specific1caught: _ _main_ _.Specific2We’ll revisit the sys.exc_info call used here in the next chapter—it’s how we cangrab hold of the most recently raised exception in a generic fashion. Briefly, for classbasedexceptions, the first item in its result is the class of the exception raised, andthe second is the actual instance raised. Apart from this method, there is no otherway to determine exactly what happened in an empty except clause like this one thatcatches everything.Notice that we call classes to make instances in the raise statements here; as we’ll seewhen we formalize raise statement forms later in this section, an instance is alwayspresent when raising a class-based exception. This code also includes functions thatraise instances of all three of our classes as exceptions, as well as a top-level try thatcalls the functions, and catches General exceptions (the same try also catches thetwo specific exceptions, because they are subclasses of General).One more note: the current <strong>Python</strong> documentation states that it is preferred (thoughnot required) that user-defined exception classes inherit from the built-in exceptionnamed Exception. To do this, we would rewrite the first line of our classexc.py file asfollows:class General(Exception): passclass Specific1(General): passclass Specific2(General): passAlthough this isn’t required, and standalone exception classes work fine today, preferredthings have a way of becoming requirements in <strong>Python</strong> over time. If you wantto future-proof your code, inherit from Exception in your root superclass, as shownhere. Doing so also provides your class with some useful interfaces and tools for free,by inheritance—for example, the Exception class comes with _ _init_ _ constructorlogic, which automatically attaches constructor arguments to class instances.Class-Based Exceptions | 605

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

Saved successfully!

Ooh no, something went wrong!