捕获并立即引发异常时避免“在处理上述异常期间发生另一个异常”

For*_*t17 2 python error-handling

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

显然,该代码会引发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'"
Run Code Online (Sandbox Code Playgroud)

虽然我理解 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)
Run Code Online (Sandbox Code Playgroud)

这将错误消息缩短为:

Traceback (most recent call last):

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

KeyError: "Bad key:'b'"
Run Code Online (Sandbox Code Playgroud)

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

rob*_*xyz 6

根据这个答案,您需要添加from None到您的例外中。

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