Catching Thread Exceptions in Python Multithreading
In Python, multithreading allows concurrent execution of multiple tasks. However, handling exceptions within a child thread poses challenges, as the exception occurs in a separate context.
Problem Explained
When a child thread throws an exception, it's not directly caught in the parent thread. The thread_obj.start() method returns immediately, while the child thread operates independently.
Solution Using Queue and sys.exc_info()
To communicate the exception information back to the parent thread, we can use a queue for message passing. Here's an example:
import sys import threading import queue class ExcThread(threading.Thread): def __init__(self, bucket): threading.Thread.__init__(self) self.bucket = bucket def run(self): try: raise Exception('An error occured here.') except Exception: self.bucket.put(sys.exc_info()) def main(): bucket = queue.Queue() thread_obj = ExcThread(bucket) thread_obj.start() while True: try: exc = bucket.get(block=False) except queue.Empty: pass else: exc_type, exc_obj, exc_trace = exc # deal with the exception print(exc_type, exc_obj) print(exc_trace) thread_obj.join(0.1) if thread_obj.isAlive(): continue else: break if __name__ == '__main__': main()
Explanation:
This approach allows the parent thread to handle exceptions from the child thread effectively.
The above is the detailed content of How to Catch Exceptions from Child Threads in Python Multithreading?. For more information, please follow other related articles on the PHP Chinese website!