Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 623
sds Avatar asked Jul 22 '19 15:07

sds


People also ask

How can an exception be re raised?

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.).

How do you raise an exception from another exception?

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.

How do you're raise the exception currently being handled Python?

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.


1 Answers

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.

like image 75
Prune Avatar answered Oct 24 '22 11:10

Prune