繁体   English   中英

如何使用自定义 errorType 进行异常处理?

[英]How do i use exception handling with custom errorType?

这个问题是关于异常处理的。 基本上,我需要创建一个异常 class 但不是我所学的

class ExpenditureException(Exception):
    pass

我当前的异常 class 需要是这样的

class ExpenditureException(Exception):
    def __init__(self, message, errorType):
        super().__init__(message)
        self._errorType = errorType

    @property
    def errorType(self):
        return self._errorType

class Expenditure:
    def __init__(self, expenditureDate, amount, expenditureType):
        self._date = expenditureDate
        self._amount = amount
        if amount < 0:
            raise ExpenditureException(f'{amount} cannot be negative')
        self._type = expenditureType

我遇到的问题是我如何使用errorType? 在我提出的上述错误中,我需要将其放在 errorType 'Amount' 下,但我不知道该怎么做。 我用字典吗?

与其维护errorType属性,不如在异常 class 中,为什么不使用 inheritance 来表示它的含义? 换句话说,我建议您创建异常类的 inheritance 层次结构。 例如:

class ExpenditureException(Exception):
    pass

class AmountException(ExpenditureException):
    def __init__(self, amount):
        super().__init__(f'The amount, {amount}, cannot be negative')

class DateException(ExpenditureException):
    def __init__(self, date):
        super().__init__(f'The date, {date}, is invalid')


class Expenditure:
    def __init__(self, expenditureDate, amount, expenditureType):
        self._date = expenditureDate
        self._amount = amount
        if amount < 0:
            raise AmountException(amount)
        if date[0:4] != '2019':
            raise DateException(date)
        self._type = expenditureType

try:
    e = Expenditure('2019-11-01', -1, 'Travel')
except ExpenditureException as ex:
    print(ex.__class__.__name__, ': ', ex, sep='')

印刷:

AmountException: The amount, -1, cannot be negative

您始终可以测试实际的 class 类型以查看您遇到的异常类型,例如:

if isinstance(ex, AmountException): do_something()

这替代了维护显式的errorType属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM