如何将异常处理与自定义errorType一起使用?

时间:2019-11-16 14:17:08

标签: python-3.x exception

这个问题是关于异常处理的。基本上,我需要创建一个异常类,但是要代替我刚刚被教过的东西

class ExpenditureException(Exception):
    pass

我当前的异常类必须是这样的

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'下,但我不知道该怎么做。我使用字典吗?

1 个答案:

答案 0 :(得分:0)

除了在异常类中保留errorType属性外,为什么不使用继承的含义呢?换句话说,我建议您创建异常类的继承层次结构。例如:

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

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

if isinstance(ex, AmountException): do_something()

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