gpt4 book ai didi

Python:必须导入非内置异常才能捕获它们吗?

转载 作者:行者123 更新时间:2023-11-28 20:06:03 25 4
gpt4 key购买 nike

我正在尝试使用以下 try-except block 捕获 requests 库抛出的一些异常:

 try:
get = requests.get((requester.batchesUrl)+str(id)+'/', auth=requester.auth)
except (ConnectionRefusedError, ConnectionError, MaxRetryError) as e:
print("CAUGHT ECONNECTION ERROR")
raise type(e)(str(e) + "Additional Info: Method couldn't connect to website, check that your server is running"
).with_traceback(sys.exc_info()[2])

但我没有捕获异常并将 "Additional Info:" 添加到 args,而是得到了 NameError: global name 'MaxRetryError' is not defined. 现在我知道了MaxRetryError 是 urllib3.exceptions.MaxRetryError 中的异常。我必须导入这些非内置异常才能捕获它们吗?考虑到可能需要注意的可能异常的数量,这对我来说似乎很冗长。

运行:Python 3.3、Windows 7。

最佳答案

您必须总是总是总是在可访问范围内拥有一个名称,然后您才能在不抛出异常的情况下引用它。如果这意味着进口,那就这样吧。

关于Python:必须导入非内置异常才能捕获它们吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25254340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com