Home > Article > Backend Development > How to Catch Child Thread Exceptions in a Parent Thread in Python?
In Python, multithreaded programming allows you to execute tasks concurrently. However, exception handling in multithreaded contexts can be challenging. This article addresses a specific issue: catching exceptions that occur in a child thread from the parent thread.
The problem arises because the child thread operates independently with its own context and stack. Exceptions thrown in the child thread are not immediately visible to the parent thread. Traditional try-except blocks in the parent thread, as shown below, will not work:
try: threadClass.start() ##### **Exception takes place here** except: print "Caught an exception"
To address this, we can utilize message passing. The child thread can send exception information to the parent thread using a shared data structure like a queue.
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()
In this example:
Using message passing allows for efficient communication of exceptions between threads.
The above is the detailed content of How to Catch Child Thread Exceptions in a Parent Thread in Python?. For more information, please follow other related articles on the PHP Chinese website!