简体   繁体   中英

How do i use exception handling with custom errorType?

This question is about exception handling. Basically, i need to create an exception class but instead of what i have been taught where it is just

class ExpenditureException(Exception):
    pass

My current exception class needs to be something like that

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

The problem I am having is that how do i use the errorType? In the above error i have raised, i need to place it under the errorType 'Amount' but i have no idea how to do so. Do i use a dictionary?

Rather than maintain an errorType attribute, in the exception class, why not use inheritance for what it was meant? In other words, I suggest that you create an inheritance hierarchy of exception classes. For example:

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='')

Prints:

AmountException: The amount, -1, cannot be negative

You can always test the actual class type to see what type of exception you got, for instance:

if isinstance(ex, AmountException): do_something()

This substitutes for maintaining an explicit errorType attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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