我正在尝试在 Python 中创建自定义错误异常。如果参数不在字典中,我希望引发错误_fetch_currencies()
。
自定义错误:
class CurrencyDoesntExistError:
def __getcurr__(self):
try:
return _fetch_currencies()[self]
except KeyError:
raise CurrencyDoesntExistError()
我如何将它写入我的函数:
def convert(amount, from_curr, to_curr, date=str(datetime.date.today())):
"""
Returns the value obtained by converting the amount 'amount' of the
currency 'from_curr' to the currency 'to_curr' on date 'date'. If date is
not given, it defaults the current date.
"""
try:
from_value = float(get_exrates(date)[from_curr])
to_value = float(get_exrates(date)[to_curr])
C = amount * (to_value / from_value)
return C
except CurrencyDoesntExistError:
print('Currency does not exist')
我目前收到错误消息:
TypeError: catching classes that do not inherit from BaseException is not allowed
如果我except KeyError:
在我的函数中使用convert
它会运行,但是引发这个自定义错误异常的正确方法是什么?