Proper way to declare custom exceptions in modern Python?

后端 未结 11 1634
栀梦
栀梦 2020-11-22 08:04

What\'s the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instan

11条回答
  •  感情败类
    2020-11-22 08:23

    see how exceptions work by default if one vs more attributes are used (tracebacks omitted):

    >>> raise Exception('bad thing happened')
    Exception: bad thing happened
    
    >>> raise Exception('bad thing happened', 'code is broken')
    Exception: ('bad thing happened', 'code is broken')
    

    so you might want to have a sort of "exception template", working as an exception itself, in a compatible way:

    >>> nastyerr = NastyError('bad thing happened')
    >>> raise nastyerr
    NastyError: bad thing happened
    
    >>> raise nastyerr()
    NastyError: bad thing happened
    
    >>> raise nastyerr('code is broken')
    NastyError: ('bad thing happened', 'code is broken')
    

    this can be done easily with this subclass

    class ExceptionTemplate(Exception):
        def __call__(self, *args):
            return self.__class__(*(self.args + args))
    # ...
    class NastyError(ExceptionTemplate): pass
    

    and if you don't like that default tuple-like representation, just add __str__ method to the ExceptionTemplate class, like:

        # ...
        def __str__(self):
            return ': '.join(self.args)
    

    and you'll have

    >>> raise nastyerr('code is broken')
    NastyError: bad thing happened: code is broken
    

提交回复
热议问题