-1

我正在尝试在 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它会运行,但是引发这个自定义错误异常的正确方法是什么?

4

3 回答 3

2

如果您只想在引发异常时打印一条消息,请执行以下操作:

class CurrencyDoesntExistError(Exception):
    pass

raise CurrencyDoesntExistError("Currency does not exist")
于 2015-04-30T12:51:28.080 回答
2

正如其他人已经说过的那样,您的类定义缺少基类引用存在问题。

但是,如果您有一个模块和一个同名的类,并且您导入的是模块而不是类,也会发生这种情况。

例如模块和类被称为 MyException。

import MyException

会给你这个错误,而:

from MyException import MyException

按预期工作。

于 2019-07-18T14:28:53.167 回答
1

您应该将类​​定义更改为:

class CurrencyDoesntExistError(BaseException):
    ...

文档:https ://docs.python.org/3.1/tutorial/classes.html#inheritance

于 2015-04-30T12:51:21.883 回答