Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách catch exception của thread trong caller thread trong Python?

Vấn đề là thread_obj.start() trả về ngay lập tức. Child thread bạn start thực thi trong context riêng, stack riêng. Bất kỳ exception nào xảy ra đó nằm trong context của child thread. Bạn phải communicate thông tin này đến parent thread bằng cách passing message.

Code có thể viết lại như sau:

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