创建合作的异常

Creating exceptions that are co-operative

Pythondocs状态:

Programs may name their own exceptions by creating a new exception class (see Classes for more about Python classes). Exceptions should typically be derivedfrom the Exception class, either directly or indirectly.

...

When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions.

来自 Python’s super() considered super!:

Each level strips-off the keyword arguments that it needs so that the final empty dict can be sent to a method that expects no arguments at all (for example, object.init expects zero arguments)

假设我有以下 StudentValueErrorMissingStudentValue 异常。

class StudentValueError(Exception):
    """Base class exceptions for Student Values"""
    def __init__(self, message, **kwargs):
        super().__init__(**kwargs)
        self.message = message # You must provide at least an error message.


class MissingStudentValue(StudentValueError):
    def __init__(self, expression, message, **kwargs):
        super().__init__(message, **kwargs)
        self.expression = expression

    def __str__(self):
        return "Message: {0} Parameters: {1}".format(self.message, self.expression)

我想创建合作的异常。我有两个问题:

  1. 在那种情况下,Exception class 构造函数需要零个参数(空 dict),正确吗?
  2. 我的示例是否违反了 LSP?

提供的已接受答案 here 继承自 ValueError

Exception 不接受关键字参数,它只通过 *args 接受可变数量的位置参数,因此您需要将 **kwargs 更改为 *args。我还建议将 messageexpression*args 一起传递给 super() 调用。毕竟,这个例子,可能不违反 LSP:

class StudentValueError(Exception):
    """Base class exceptions for Student Values"""
    def __init__(self, message='', *args):
        super().__init__(message, *args)
        self.message = message 


class MissingStudentValue(StudentValueError):
    def __init__(self, message='', expression='', *args):
        super().__init__(message, expression, *args)
        self.expression = expression

    def __str__(self):
        return "Message: {0} Parameters: {1}".format(self.message, self.expression)


e = Exception('message', 'expression', 'yet_another_argument')
print(e)
e = StudentValueError('message', 'expression', 'yet_another_argument')
print(e)
e = MissingStudentValue('message', 'expression', 'yet_another_argument')
print(e)
e = MissingStudentValue()
print(e)