gpt4 book ai didi

python - 捕获并立即引发异常时避免 "During handling of the above exception, another exception occurred"

转载 作者:行者123 更新时间:2023-12-02 18:54:17 25 4
gpt4 key购买 nike

my_dictionary = {'a':1}
try:
my_dictionary['b']
except KeyError as e:
raise KeyError('Bad key:' + str(e))

该代码显然会引发KeyError:

Traceback (most recent call last):

File "----.py", line 11, in <module>
my_dictionary['b']

KeyError: 'b'


During handling of the above exception, another exception occurred:

Traceback (most recent call last):

File "----.py", line 13, in <module>
raise KeyError('Bad key:' + str(e))

KeyError: "Bad key:'b'"

虽然我理解 Python 需要说明 except 部分如何创建自己的错误,但我希望不显示第一个 KeyError 。我想出的解决方法是:

my_dictionary = {'a':1}
err_msg = None
try:
my_dictionary['b']
except KeyError as e:
err_msg = str(e)
if type(err_msg) != type(None):
raise KeyError('Bad key:' + err_msg)

将错误消息缩短为:

Traceback (most recent call last):

File "----.py", line 23, in <module>
raise KeyError('Bad key:' + err_msg)

KeyError: "Bad key:'b'"

有没有更Pythonic的方法来做到这一点?

最佳答案

来自this answer ,您需要将 from None 添加到您的异常中。

my_dictionary = {'a':1}
try:
my_dictionary['b']
except KeyError as e:
raise KeyError('Bad key:' + str(e)) from None

关于python - 捕获并立即引发异常时避免 "During handling of the above exception, another exception occurred",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66379099/

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