重新提炼Python异常并保留堆栈跟踪 [英] Re-raise Python exception and preserve stack trace
问题描述
import threading
import sys
class FailingThread(threading.Thread):
def run(self):
try:
raise ValueError('x')
除了ValueError:
self.exc_info = sys.exc_info()
failingThread = FailingThread()
failingThread.start()
failingThread.join()
print failingThread.exc_info
raise failingThread.exc_info [1]
这基本上可以产生以下输出:
(< type'exceptions.ValueError '> ValueError('x',),< traceback对象在0x1004cc320>)
追溯(最近的最后一次调用):
文件test.py,第16行,<模块> ;
raise failingThread.exc_info [1]
但是,异常的来源指向行16,重新发生的地方。原来的例外来自第7行。如何修改主要线程,以便输出如下:
追溯(最近的最后一次调用):
文件test.py,第7行,< module>
您需要使用所有三个参数来加注: / p>
raise failingThread.exc_info [0],failingThread.exc_info [1],failingThread.exc_info [2]
传递跟踪对象作为第三个参数保留堆栈。
从 help('raise')
:
如果第三个对象存在而不是
无
,它必须是追溯
对象(请参阅标准类型层次结构),它是
代替当前位置作为
异常发生的地方。如果第三个对象存在,而不是
traceback对象或None
,则会引发TypeError
异常。
三个表达式的raise
可以在except子句中透明地重新引发一个异常
,但是raise
没有表达式
应该是首选,如果重新提出的异常是当前范围内最多
最近活动的异常。
< blockquote>
在这种特殊情况下,您不能使用no表达式版本。
I'm trying to catch an exception in a thread and re-raise it in the main thread:
import threading import sys class FailingThread(threading.Thread): def run(self): try: raise ValueError('x') except ValueError: self.exc_info = sys.exc_info() failingThread = FailingThread() failingThread.start() failingThread.join() print failingThread.exc_info raise failingThread.exc_info[1]
This basically works and yields the following output:
(<type 'exceptions.ValueError'>, ValueError('x',), <traceback object at 0x1004cc320>) Traceback (most recent call last): File "test.py", line 16, in <module> raise failingThread.exc_info[1]
However, the source of the exception points to line 16, where the re-raise occurred. The original exception comes from line 7. How do I have to modify the main thread so that the output reads:
Traceback (most recent call last): File "test.py", line 7, in <module>
解决方案You need to use all three arguments to raise:
raise failingThread.exc_info[0], failingThread.exc_info[1], failingThread.exc_info[2]
passing the traceback object in as the third argument preserves the stack.
From
help('raise')
:If a third object is present and not
None
, it must be a traceback object (see section The standard type hierarchy), and it is substituted instead of the current location as the place where the exception occurred. If the third object is present and not a traceback object orNone
, aTypeError
exception is raised. The three-expression form ofraise
is useful to re-raise an exception transparently in an except clause, butraise
with no expressions should be preferred if the exception to be re-raised was the most recently active exception in the current scope.In this particular case you cannot use the no expression version.
这篇关于重新提炼Python异常并保留堆栈跟踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!