O'Reilly logo

Python in a Nutshell by Alex Martelli

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Exception Objects

Exceptions are instances of subclasses of the built-in Exception class. For backward compatibility, Python also lets you use strings, or instances of any class, as exception objects, but such usage risks future incompatibility and gives no benefits. An instance of any subclass of Exception has an attribute args, the tuple of arguments used to create the instance. args holds error-specific information, usable for diagnostic or recovery purposes.

The Hierarchy of Standard Exceptions

All exceptions that Python itself raises are instances of subclasses of Exception. The inheritance structure of exception classes is important, as it determines which except clauses handle which exceptions.

The SystemExit class inherits directly from Exception. Instances of SystemExit are normally raised by the exit function in module sys (covered in Chapter 8).

Other standard exceptions derive from StandardError, a direct subclass of Exception. Three subclasses of StandardError, like StandardError itself and Exception, are never instantiated directly. Their purpose is to make it easier for you to specify except clauses that handle a broad range of related errors. These subclasses are:

ArithmeticError

The base class for exceptions due to arithmetic errors (i.e., OverflowError, ZeroDivisionError, FloatingPointError)

LookupError

The base class for exceptions that a container raises when it receives an invalid key or index (i.e., IndexError, KeyError)

EnvironmentError

The ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required