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.

maintenance issues than strings do. Moreover, class-based exceptions can supportstate retention and inheritance in ways that strings cannot—concepts we’ll exploreby example later in this chapter.Built-in Exception ClassesI didn’t really pull the prior section’s examples out of thin air. Although user-definedexceptions may be identified by string or class objects, all built-in exceptions that<strong>Python</strong> itself may raise are predefined class objects instead of strings. Moreover, theyare organized into a shallow hierarchy with general superclass categories and specificsubclass types, much like the exceptions class tree we developed earlier.All the familiar exceptions you’ve seen (e.g., SyntaxError) are really just predefinedclasses, available both as built-in names (in the module _ _builtin_ _), and asattributes of the standard library module exceptions. In addition, <strong>Python</strong> organizesthe built-in exceptions into a hierarchy, to support a variety of catching modes. Forexample:ExceptionThe top-level root superclass of exceptions.StandardErrorThe superclass of all built-in error exceptions.ArithmeticErrorThe superclass of all numeric errors.OverflowErrorA subclass that identifies a specific numeric error.And so on—you can read further about this structure in either the <strong>Python</strong> librarymanual, or the help text of the exceptions module (see Chapters 4 and 14 for help onhelp):>>> import exceptions>>> help(exceptions)...lots of text omitted...The built-in class tree allows you to choose how specific or general your handlerswill be. For example, the built-in exception ArithmeticError is a superclass for morespecific exceptions such as OverflowError and ZeroDivisionError. By listingArithmeticError in a try, you will catch any kind of numeric error raised; by listingjust OverflowError, you will intercept just that specific type of error, and no others.Similarly, because StandardError is the superclass of all built-in error exceptions, youcan generally use it to select between built-in errors and user-defined exceptions in atry:try:action( )Class-Based Exceptions | 609

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

Saved successfully!

Ooh no, something went wrong!