sds
sds

Reputation: 60004

How to re-raise an exception with additional information?

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?

Upvotes: 6

Views: 109

Answers (1)

Prune
Prune

Reputation: 77837

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.

Upvotes: 2

Related Questions