2
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?

Forklift17
  • 2,245
  • 3
  • 20
  • 32

2 Answers2

5

From this answer, you need to add from None to your exception.

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

If you have a specific thing that you want to print instead of showing the stack trace, you can do that by just using print and then sys.exit(1), which is probably as pythonic as you can get. Another thing you can do is to raise KeyError('Bad key:' + str(e)) from e, which replaces "During handling of the above exception, another exception occurred:" with "The above exception was the direct cause of the following exception:". I don't think there's a way to do exactly what you asked, because the whole reason that error messages are generated like that is because you should be given all the information unless you explicitly specify some other behaviour. Uncaught exceptions generally represent some mistake in your code - they aren't supposed to happen normally, so there wouldn't be a need to make the formatting of the error messages too customizable.

Lionel Foxcroft
  • 1,584
  • 3
  • 9
  • 23