Linux/Unix > Python Essential Reference, Second Edition > 5. Control Flow > Defining New Exceptions | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137104016132043219194028022

### Defining New Exceptions

All the built-in exceptions are defined in terms of classes. To create a new exception, create a new class definition that inherits from `exceptions. Exception` such as the following:

    import exceptions
    # Exception class
    class NetworkError(exceptions.Exception):
         def _ _init_ _(self,args=None):
             self.args = args

The name `args` should be used as shown. This allows the value used in the `raise` statement to be properly printed in tracebacks and other diagnostics. In other words,

    raise NetworkError, "Cannot find host."

creates an instance of `NetworkError` using the call

    NetworkError("Cannot find host.")

The object that is created will print itself as `NetworkError: Cannot find host`. If you use a name other than `self.args` or you don’t store the argument, this feature won’t work correctly.

When an exception is raised, the optional value supplied in the `raise` statement is used as the argument to the exception’s class constructor. If the constructor for an exception requires more than one argument, it can be raised in two ways:

    import exceptions
    # Exception class
    class NetworkError(exceptions.Exception):
         def _ _init_ _(self,errno,msg):
         self.args = (errno, msg)
         self.errno = errno
         self.errmsg = msg

    # Raises an exception (multiple arguments)
    def error2():
         raise NetworkError(1, 'Host not found')

    # Raises an exception (multiple arguments)
    def error3():
         raise NetworkError, (1, 'Host not found')

Class-based exceptions enable you to create hierarchies of exceptions. For instance, the `NetworkError` exception defined earlier could serve as a base class for a variety of more specific errors. For example:

    class HostnameError(NetworkError):
        pass

    class TimeoutError(NetworkError):
        pass

    def error3():
        raise HostnameError

    def error4():
        raise TimeoutError

    try:
        error3()
    except NetworkError:
        import sys
        print sys.exc_type    # Prints exception type

In this case, the `exceptNetworkError` statement catches any exception derived from `NetworkError`. To find the specific type of error that was raised, examine the variable `sys.exc_type`. Similarly, the `sys.exc_value` variable contains the value of the last exception. Alternatively, the `sys.exc_info()` function can be used to retrieve exception information in a manner that doesn’t rely on global variables and is thread-safe.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.