In Python, how do I inspect and then re-raise an exception while maintaining the original call stack?
我有一种情况,我正在捕获一个特定的异常类型,检查异常的消息,检查它是否实际上是我想要捕获的异常,然后重新引发异常,如果不是:
1 2 3 4 5 6 7 | try: # do something exception-prone except FooException as e: if e.message == 'Something I want to handle': # handle the exception else: raise e |
这很好,有一个问题。在我重新引发异常的情况下,该异常现在发生在我重新引发它的行(即
因此我的问题是:在保持原始异常位置的同时捕获它之后,是否有任何方法可以重新引发或以其他方式"传递"异常?
注意:如果您想知道实际情况是什么:我使用
做就是了:
1 | raise |
而不是
If no expressions are present, raise re-raises the last exception that was active in the current scope. If no exception is active in the current scope, a TypeError exception is raised indicating that this is an error (if running under IDLE, a Queue.Empty exception is raised instead).