Custom Exception Classes
You can subclass any of the standard exception classes in order to define your own exception class. Often, such a subclass adds nothing more than a docstring:
class InvalidAttribute(AttributeError): "Used to indicate attributes that could never be valid"
As covered in The pass Statement, you don’t need a pass
statement to make up the body of this class; the docstring (which you should always write) is quite sufficient to keep Python happy. Best style for such “empty” classes, just like for “empty” functions, is to have a docstring and no pass
.
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 that can 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 "+name
Now client code can be more selective in its handlers. For example:
s = SomeFunkyClass( ) try: value = getattr(s, thename) except InvalidAttribute, ...
Get Python in a Nutshell, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.