I expect a python function I use to raise a KeyError
, in case the user of my script entered a wrong value.
When this happens, I want to raise a ValueError
, not a KeyError
. I tried to catch the KeyError
, then raise a ValueError
instead. I then get both.
For example:
def func(my_dict):
return my_dict["my_key"]
a = {}
try:
func(a)
except KeyError as e:
raise ValueError("Replaced exception")
results in this:
$ python3 except.py
Traceback (most recent call last):
File "except.py", line 7, in <module>
func(a)
File "except.py", line 2, in func
return my_dict["my_key"]
KeyError: 'my_key'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "except.py", line 9, in <module>
raise ValueError("Replaced exception")
ValueError: Replaced exception
I don't care about the KeyError
itself, I just want to tell the user about the ValueError
.
How can I catch the KeyError
, but discard it? Is it bad practice? How should I organize this instead?