Source

The exceptions module

This module provides the standard exception hierarchy. It’s automatically imported when Python starts, and the exceptions are added to the `__builtin__ <builtin.htm>`__ module. In other words, you usually don’t need to import this module.

This is a Python module in 1.5.2, and a built-in module in 2.0 and later.

The following standard exceptions are defined by this module:

You can create your own exception classes. Just inherit from the built-in Exception class (or a proper standard exception), and override the constructor and/or __str__ method as necessary.

Example: Using the exceptions module

# File: `exceptions-example-1.py <exceptions-example-1.py>`__

# python imports this module by itself, so the following
# line isn't really needed
# import exceptions

class HTTPError(Exception):
    # indicates an HTTP protocol error
    def __init__(self, url, errcode, errmsg):
        self.url = url
        self.errcode = errcode
        self.errmsg = errmsg
    def __str__(self):
        return (
            "" %
            (self.url, self.errcode, self.errmsg)
            )

try:
    raise HTTPError("http://www.python.org/foo", 200, "Not Found")
except HTTPError, error:
    print "url", "=>", error.url
    print "errcode", "=>", error.errcode
    print "errmsg", "=>", error.errmsg
    raise # reraise exception
$ python exceptions-example-1.py
url => http://www.python.org/foo
errcode => 200
errmsg => Not Found
Traceback (innermost last):
  File "exceptions-example-1", line 16, in ?
HTTPError: