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




11.7.1 Exceptions as Derived Classes

As described earlier user-defined exceptions can be identified by classes. Using this mechanism it is possible to create extensible hierarchies of exceptions.

There are two valid (semantic) forms for the raise statement:

    raise Class, instance
    raise instance

In the first form, instance must be an instance of Class or of a class derived from it. The second form is a shorthand for:

    raise instance.__class__, instance

A class in an except clause is compatible with an exception if it is the same class or a base class thereof (but not the other way around --- an except clause listing a derived class is not compatible with a base class). For example, the following code will print B, C, D in that order:

    class B:
    class C(B):
    class D(C):
    for c in [B, C, D]:
            raise c()
        except D:
            print "D"
        except C:
            print "C"
        except B:
            print "B"

Note that if the except clauses were reversed (with ‘except B’ first), it would have printed B, B, B -- the first matching except clause is triggered.

When an error message is printed for an unhandled exception which is a class, the class name is printed, then a colon and a space, and finally the instance converted to a string using the built-in function str().

  Published under the terms of the Python License Design by Interspire