Python reports, say, KeyError
with only the missing key, not the dict in which the key was not found.
I want to "fix" this in my code:
d = {1:"2"}
try:
d[5]
except Exception as e:
raise type(e)(*(e.args+(d,)))
----> 5 raise type(e)(*e.args+(d,))
KeyError: (5, {1: '2'})
Alas, the stack points to the wrong line.
2nd attempt:
d = {1:"2"}
try:
d[5]
except Exception as e:
e.args += (d,)
raise e
----> 3 d[5]
KeyError: (5, {1: '2'})
Here the stack is correct.
Is this the right way to do it? Is there an even better way?
Problem – Reraising the exception, that has been caught in the except block. Code #1: Using raise statement all by itself. This problem typically arises when there is no need to take any action in response to an exception (e.g., logging, cleanup, etc.).
Let's consider a situation where we want to raise an exception in response to catching a different exception but want to include information about both exceptions in the traceback. To chain exceptions, use the raise from statement instead of a simple raise statement.
Python Language Exceptions Re-raising exceptions In this case, simply use the raise statement with no parameters. But this has the drawback of reducing the exception trace to exactly this raise while the raise without argument retains the original exception trace.
Yes, you've done the "right thing": add the information to the exception variable as appropriate, and then re-raise the exception.
Your first attempt created a new exception of the same type, which is why the stack pointer moved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With