Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the key information from a KeyError

Is there a way to get the key that raised a KeyError?

or in general, where can I find (if available) properties of an Exception?

like image 228
xcorat Avatar asked Dec 07 '25 23:12

xcorat


1 Answers

Exceptions have a .args attribute which is a tuple; for a KeyError exception that tuple contains the key that triggered the exception:

>>> try:
...     {}['foo']
... except KeyError as ex:
...     print(ex.args[0])
... 
foo
like image 166
Martijn Pieters Avatar answered Dec 10 '25 13:12

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!