如何在 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