In Python, how do I check and then raise the exception again while keeping the original call stack?

I have a situation where I catch a specific type of exception by checking the exception message to see if it is the exception that I want to catch, and then re-throw the exception if not:

try: # do something exception-prone except FooException as e: if e.message == 'Something I want to handle': # handle the exception else: raise e 

This works fine, with one problem. In the case when I raise the exception again, this exception now appears in the line that I raised again (i.e., raise e ), and not in the place where the exception originally occurred. This is not ideal for debugging, where you want to know where the original exception occurred.

So my question is: is there a way to re-pass the exception once or another after catching it while maintaining the original location of the exception?

NOTE. If you're curious about the real situation: I dynamically import some modules using __import__ . I catch ImportError in order to correctly deal with the fact that none of these modules exist. However, if in any of these modules there is an import statement that raises ImportError , I want those "real" (from the point of view of my application) exceptions to be raised - and at the original location as debugging tools.

+7
source share
1 answer

Just do:

 raise 

instead of raise e . See the section of the manual for exception collection , as well as a link to :

If no expressions are present, the raise repeatedly raises the last exception that was active in the current area. If the exception is not active in the current scope, a TypeError exception is raised, indicating that it is an error (if executed under IDLE, a Queue.Empty exception is raised instead).

+7
source

All Articles