如何在 Python 中在调用线程中捕获线程的异常?
问题在于 thread_obj.start() 会立即返回。你启动的子线程在其自己的上下文中执行,在自己的栈中执行。在那里发生的任何异常都在子线程的上下文中。你必须通过传递一些消息将此信息传达给父线程。
代码可以重新编写如下
import sys
import threading
import Queue
class ExcThread(threading.Thread):
def __init__(self, foo):
threading.Thread.__init__(self)
self.foo = foo
def run(self):
try:
raise Exception('An error occurred here.')
except Exception:
self.foo.put(sys.exc_info())
def main():
foo = Queue.Queue()
thread_obj = ExcThread(foo)
thread_obj.start()
while True:
try:
exc = foo.get(block=False)
except Queue.Empty:
pass
else:
exc_type, exc_obj, exc_trace = exc
print exc_type, exc_obj
print exc_trace
thread_obj.join(0.1)
if thread_obj.isAlive():
continue
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP