Custom Exception Classes
You can subclass any of the standard exception classes in order to define your own exception class. Typically, such a subclass adds nothing more than a docstring:
class InvalidAttribute(AttributeError):
"Used to indicate attributes that could never be valid"Given the semantics of
try/except, raising a custom
exception class such as InvalidAttribute is almost
the same as raising its standard exception superclass,
AttributeError. Any except
clause able to handle AttributeError can handle
InvalidAttribute just as well. In addition, client
code that knows specifically about your
InvalidAttribute custom exception class can handle
it specifically, without having to handle all other cases of
AttributeError if it is not prepared for those.
For example:
class SomeFunkyClass(object):
"much hypothetical functionality snipped"
def __getattr__(self, name):
"this __getattr__ only clarifies the kind of attribute error"
if name.startswith('_'):
raise InvalidAttribute, "Unknown private attribute "+name
else:
raise AttributeError, "Unknown attribute "+nameNow client code can be more selective in its handlers. For example:
s = SomeFunkyClass( )
try:
value = getattr(s, thename)
except InvalidAttribute, err:
warnings.warn(str(err))
value = None
# other cases of AttributeError just propagate, as they're unexpectedA special case of custom exception class that you may sometimes find useful is one that wraps another exception and adds further information. To gather information about ...