defining, raising and catching exceptions

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Aug 6 03:38:42 CEST 2010


On Fri, 06 Aug 2010 01:37:17 +0100, MRAB wrote:

> The correct way to create your own exceptions is to call the
> superclass's __init__ method:
> 
> 
>  >>> class NetActiveError(RuntimeError):
> ...     def __init__(self, error):
> ...         RuntimeError.__init__(self, error)

As given, that's pointless since you're neither overriding (replacing) 
nor overloading the base class method. Since NetActiveError inherits ALL 
behaviour and state from RuntimeError, there's no need to overload 
anything at all, so the correct way to subclass is to simply give the 
subclass a name and (optionally) a docstring:

class NetActiveError(RuntimeError):
    """Description of error goes here."""


The only change from the OP's code is that instead of defining a non-
standard error attribute, it uses the standard message and args 
attributes:

>>> e = NetActiveError('network already running')
>>> e.message
'network already running'
>>> e.args
('network already running',)




-- 
Steven



More information about the Python-list mailing list