my_dictionary = {'a':1}
try:
my_dictionary['b']
except KeyError as e:
raise KeyError('Bad key:' + str(e))
That code, obviously, will raise a 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'"
While I understand the need for Python to state how the except
part created its own error, I'd like for that first KeyError
not to be shown. A workaround I came up with is this:
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)
which shortens the error message to this:
Traceback (most recent call last):
File "----.py", line 23, in <module>
raise KeyError('Bad key:' + err_msg)
KeyError: "Bad key:'b'"
Is there a more Pythonic way of doing this?