Python中的自定义异常

2024-09-30 22:21:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Python中创建一个自定义错误异常。如果参数不在字典_fetch_currencies()中,我希望引发错误。在

自定义错误:

class CurrencyDoesntExistError:
    def __getcurr__(self):
        try:
            return _fetch_currencies()[self]
        except KeyError:
            raise CurrencyDoesntExistError()

如何将其写入我的函数:

^{pr2}$

我当前收到错误消息:

TypeError: catching classes that do not inherit from BaseException is not allowed

如果我在函数convert中使用except KeyError:,它将运行,但引发此自定义错误异常的正确方法是什么?在


Tags: 函数self参数字典def错误notfetch
3条回答

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

class CurrencyDoesntExistError(Exception):
    pass

raise CurrencyDoesntExistError("Currency does not exist")

您应该将类定义更改为:

class CurrencyDoesntExistError(BaseException):
    ...

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

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

正如我所提到的,如果有一个模块和一个同名的类,并且导入模块而不是类,也会发生这种情况。在

例如,模块和类被称为MyException。在

import MyException

将显示此错误,而:

^{pr2}$

按预期工作。在

相关问题 更多 >