How to extract error data from KeyError in python

48 Views Asked by At

I have an excel file from which I retrieve data with pandas. I have a dictionary where keys are the same strings that I get from a cell from the excel file. For example, I have a excel cell that contains string Heattreatment 1. In my dictionary I have a key, value pair: "Heattreatment 1": 1. The problem is that if I have typos in my excel file, for example, if instead of Heattreatment 1 I write Heattreatment 123 and such a key does not exist in my dictionary, I get KeyError: 'Heattreatment 123'.

Is there a way to extract this message, so that I would say something like:

error_data = #something
print(error_data)

And the output would be: 'Heattreatment 123'

I tried:

try:
    # some code
except Exception as e:
    print(e)

But this does not work.

1

There are 1 best solutions below

0
cwiz On

Your last example should work if you catch KeyError specifically instead of the general Exception. When possible you should catch as specific of an error as possible.

try:
    # some code
except KeyError as error:
    print(error)

If your goal is to reconstruct the actual error message itself, this would also work just by catching the KeyError and reconstructing the message.

try:
    # some code
except KeyError as error:
    print(f"KeyError: '{error}'")