Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




10.5 User-defined Exceptions

Programs may name their own exceptions by creating a new exception class. Exceptions should typically be derived from the Exception class, either directly or indirectly. For example:

    >>> class MyError(Exception):
    ...     def __init__(self, value):
    ...         self.value = value
    ...     def __str__(self):
    ...         return `self.value`
    >>> try:
    ...     raise MyError(2*2)
    ... except MyError, e:
    ...     print 'My exception occurred, value:', e.value
    My exception occurred, value: 4
    >>> raise MyError, 'oops!'
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    __main__.MyError: 'oops!'

Exception classes can be defined which do anything any other class can do, but are usually kept simple, often only offering a number of attributes that allow information about the error to be extracted by handlers for the exception. When creating a module which can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions:

    class Error(Exception):
        """Base class for exceptions in this module."""
    class InputError(Error):
        """Exception raised for errors in the input.
            expression -- input expression in which
                          the error occurred
            message -- explanation of the error
        def __init__(self, expression, message):
            self.expression = expression
            self.message = message
    class TransitionError(Error):
        """Raised when an operation attempts a state
        transition that's not allowed.
            previous -- state at beginning of transition
            next -- attempted new state
            message -- explanation of why the specific
                       transition is not allowed
        def __init__(self, previous, next, message):
            self.previous = previous
   = next
            self.message = message

Most exceptions are defined with names that end in "Error," similar to the naming of the standard exceptions.

Many standard modules define their own exceptions to report errors that may occur in functions they define. More information on classes is presented in chapter section 11 Classes, "Classes."

  Published under the terms of the Python License Design by Interspire