See All Titles |
![]() ![]() Creating User-defined ExceptionsPython allows you to create your own exceptions by subclassing any standard Python exception. Note
Take a look at Chapter 5, "Object-Oriented Programming," for more details about working with classes. >>> import exceptions >>> class ConfigError (exceptions.Exception): … def __init__(self, arg=None): … self.args = arg … >>> try: … raise ConfigError("Bad hostname") … except ConfigError, e: … print e.args … Bad hostname The import statement from the previous example isn't really necessary because the exceptions module contents are automatically imported by the interpreter. Remember that you can't use the prefix "exceptions" because the exceptions module is not available in the __main__ namespace until you import it. The next example uses the class created in the previous example as a base class to create a new class. >>> class TimeoutError(ConfigError): … def printargs(self): … print self.args … >>> try: … raise TimeoutError, "Timeout" … except TimeoutError, e: … e.printargs() … Timeout As you could see, just by overriding the __init__ method, you are able to create your own exception classes. You can also change the output of a traceback message by overwriting the __str__ method. >>> class ConfigError(Exception): … def __init__(self, args=None): … self.args = args … def __str__(self): … return "\ nError in the module configuration\ n" + } … `self.args` + "\ n"… >>> raise ConfigError, "bad hostname" Traceback (innermost last): File "<stdin>", line 1, in ? __main__.ConfigError Error in the module configuration bad hostname
|
Index terms contained in this sectioncreatinguser-defined exceptions exceptions subclassing 2nd user-defined, creating import statement statements import subclassing exceptions 2nd user-defined exceptions creating |
© 2002, O'Reilly & Associates, Inc. |