【发布时间】:2018-02-05 20:48:11
【问题描述】:
我目前正在尝试实现一些代码,如果它失败了,我想引发一个带有特定消息的异常。 我想使用一个基本异常 SystemExit,它应该派生自 BaseException。我导入 sys 模块
我以这种方式提出异常:
add_ip = None
# search for the ip address associated with the equipment's mac address
for i in range(0, len(add_match)):
found = add_match[i].find(add_mac)
if found != -1:
add_ip = add_match[i].split()[0]
// it turns out that I don't find the matching IP address
if add_ip is not None:
print("@IP =\t", add_ip) # log matching IP
else:
raise (SystemExit, "failure retrieving interface's IP address")
当我遇到问题时,我最终会收到一个错误提示
TypeError: exceptions must derive from BaseException
我搜索了一个解决方案并找到了这个:I get "TypeError: exceptions must derive from BaseException" even though I did define it 并将我的代码修改为:
raise SystemExit("failure retrieving interface's IP address")
但我最终还是遇到了同样的失败...... 有谁知道我做错了什么?
谢谢你
亚历山大
编辑: 当我去定义 SystemExit 时,我明白了:
class SystemExit(BaseException):
""" Request to exit from the interpreter. """
def __init__(self, args, kwargs):
pass
code = None
【问题讨论】:
-
您的第二次尝试在我的机器上运行。你能提供一个minimal reproducible example 来证明该代码引发了 TypeError 吗?
-
您使用的是哪个版本的 Python? docs.python.org/2/library/exceptions.html#exceptions.SystemExit 表示 SystemExit 自 Python 2.5 以来就派生自 BaseException。您使用的是 Python 2.4 吗?请考虑升级。
-
你能展示你的
SystemExit类主体@A.Joly -
看起来你正在提升一个元组......
-
另外,你根本不应该有构造函数,因为
SystemExit是一个内置的异常类型,所以你不需要制作你自己的类版本。