最近,在做一个项目时遇到的了一个问题,主线程无法捕获子线程中抛出的异常。
先看一个线程类的定义
''''' Created on Oct 27, 2015 @author: wujz ''' import threading class runScriptThread(threading.Thread): def __init__(self, funcName, *args): threading.Thread.__init__(self) self.args = args self.funcName = funcName def run(self): try: self.funcName(*(self.args)) except Exception as e: raise e
很简单,传入要调用的方法,并启用一个新的线程来运行这个方法。
在主线程中,启动这个线程类的一个对象时,这要声明一个对象然后启动就可以了,示例如下
import runScriptThread,traceback if __name__=='__main__': sth = 'hello world' try: aChildThread = runScriptThread(printSth, sth) aChildThread.start() aChildThread.join() except Exception as e: print(str(traceback.format_exc()))
但是这样的代码,main方法中无法捕获子线程中的异常,原因在于start()方法将为子线程开辟一条新的栈,main方法的栈因此无法捕获到这一异常。
解决方法很简单,就是通过设置一个线程是否异常退出的flag的成员变量,当线程异常退出时,对其作一标记。然后在主线程中检查改线程运行结束后该标志位的值,如果异常,再通过sys和traceback回溯异常信息,然后抛出即可。改写后的异常类:
''''' Created on Oct 27, 2015 @author: wujz ''' import threading,traceback,sys class runScriptThread(threading.Thread): #The timer class is derived from the class threading.Thread def __init__(self, funcName, *args): threading.Thread.__init__(self) self.args = args self.funcName = funcName self.exitcode = 0 self.exception = None self.exc_traceback = '' def run(self): #Overwrite run() method, put what you want the thread do here try: self._run() except Exception as e: self.exitcode = 1 # 如果线程异常退出,将该标志位设置为1,正常退出为0 self.exception = e self.exc_traceback = ''.join(traceback.format_exception(*sys.exc_info())) #在改成员变量中记录异常信息 def _run(self): try: self.funcName(*(self.args)) except Exception as e: raise e
改写后的主线程:
import runScriptThread,traceback if __name__=='__main__': sth = 'hello world' try: aChildThread = runScriptThread(printSth, sth) aChildThread.start() aChildThread.join() except Exception as e: print(aChildThread.exc_traceback)
以上全部为本篇文章的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月23日
2024年09月23日
- 国风大师纯音系列《古筝仙子 常静演奏 十指弹一》1CD[FLAC][919MB]
- DasKapital-OneMustHaveChaosInsidetoGiveBirthtoaDancingStar(2024)[24-44.1]WAV
- 王菲.1999-《只爱陌生人》日本东芝版[低速原抓WAV+CUE]
- 张小英1987-金奖金曲第一集[新加坡版][WAV+CUE]
- 鹿晗.2015-重启【海蝶】【FLAC分轨】
- 张芸京.2012-小女孩【金牌大风】【WAV+CUE】
- 余天.2002-雄狮魅力金曲2CD(南方金点系列)【南方】【WAV+CUE】
- 银霞.1982-《结·SAYYESMYBOY》台湾复刻版[WAV+CUE]
- 梁汉文1993-火热动感[引进版][WAV+CUE]
- 梁汉文2008-EDMONDHITS48[香港]3CD[WAV+CUE]
- 国风大师纯音系列《童丽-[渭城曲]》1CD[WAV分轨][593.5MB]
- 国风大师纯音系列《许菱子《烧筝2》古筝曲集》1CD[WAV分轨][1.3GB]
- 王子异《1996 Part.2》[320K/MP3][18.29MB]
- 群星.1994-宝丽金最倾情3CD【宝丽金】【WAV+CUE】
- 乐俊亨.2024-同泪【CharioticMusic】【FLAC分轨】