python主线程捕获子线程异常

import threading
from traceback import format_exc

class ExcThread(threading.Thread):
    def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs=None, *, daemon=None):
        super(ExcThread, self).__init__()
        self.function = target
        self.args = args
        self.kwargs = kwargs
        self.exit_code = 0
        self.exception = None
        self.exc_traceback = ''

    def run(self):
        try:
            self._run()
        except Exception as e:
            self.exit_code = 1
            self.exception = e
            self.exc_traceback = format_exc()

    def _run(self):
        try:
            self.function(*self.args, **self.kwargs)
        except Exception as e:
            raise e


def test_fn():
    raise Exception('test error')


t = ExcThread(target=test_fn, args=(), kwargs={})
t.start()
t.join()
if t.exit_code != 0:
    raise t.exception
print('aaa')

 

转:https://www.cnblogs.com/zcsh/p/14357501.html

 

posted @ 2022-03-20 20:58  rmticocean  阅读(96)  评论(0)    收藏  举报