实现思路
- 自定义异常类:首先定义一个自定义异常类,以便在子线程中抛出特定的异常。
- 线程函数包装:将实际的线程执行函数包装在一个try - except块中,捕获异常并将其存储在一个共享变量中。
- 主线程检查:主线程定期检查共享变量中是否有异常,如果有则获取异常信息并进行相应处理,比如终止所有线程。
代码示例
import threading
import time
class ThreadException(Exception):
pass
def worker():
try:
# 模拟可能出现异常的操作
raise ThreadException("子线程出现异常")
except ThreadException as e:
global exception_info
exception_info = e
exception_info = None
threads = []
# 创建并启动线程
t = threading.Thread(target=worker)
threads.append(t)
t.start()
# 主线程检查异常
while True:
if exception_info:
print(f"主线程捕获到异常: {exception_info}")
# 终止所有线程(这里简单示意,实际可能需要更复杂的处理)
for thread in threads:
if thread.is_alive():
thread.join()
break
time.sleep(1)