Python线程捕获不到异常的原因是因为线程中的异常默认是不会被抛出到主线程的。
解决这个问题,可以使用try/except语句在线程内部捕获异常,并将异常信息传递给主线程。可以通过以下几种方式实现:
- 使用全局变量传递异常信息:在线程内部捕获异常,并将异常信息赋值给一个全局变量,主线程可以通过检查这个全局变量来获取异常信息。
import threading # 全局变量用于保存异常信息 global_exception = None def thread_function(): global global_exception try: # 线程逻辑 pass except Exception as e: global_exception = e # 创建线程 thread = threading.Thread(target=thread_function) # 启动线程 thread.start() # 等待线程结束 thread.join() # 检查异常信息 if global_exception: print("Thread exception:", global_exception)
- 使用线程间通信队列:创建一个队列,线程内部捕获异常后,将异常信息放入队列中,主线程可以从队列中获取异常信息。
import threading import queue # 创建队列用于线程间通信 exception_queue = queue.Queue() def thread_function(): try: # 线程逻辑 pass except Exception as e: # 将异常信息放入队列 exception_queue.put(e) # 创建线程 thread = threading.Thread(target=thread_function) # 启动线程 thread.start() # 等待线程结束 thread.join() # 检查异常信息 if not exception_queue.empty(): exception = exception_queue.get() print("Thread exception:", exception)
无论使用哪种方式,都需要在主线程中检查是否有异常发生,并处理异常信息。