I've got a situation where I'm catching a specific exception type, inspecting the exception's message to check if it's actually an exception I want to catch, and then re-raising 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 I re-raise the exception, that exception now occurs at the line I re-raised it (i.e. at raise e
), rather than at the location the exception originally occurred. This isn't ideal for debugging, where you want to know where the original exception happened.
Thus my question: is there any way to re-raise or otherwise "pass on" an exception after catching it while maintaining the original exception location?
NOTE: In case you are wondering what the actual situation is: I'm dynamically importing some modules using __import__
. I'm catching ImportError
to gracefully deal with the case that any of these modules do not exist. However, in the case that any of these modules themselves contain 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 far as debugging tools are concerned.