Home  >  Article  >  Backend Development  >  How to Catch Exceptions from Child Threads in Python Multithreading?

How to Catch Exceptions from Child Threads in Python Multithreading?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-22 10:49:11798browse

How to Catch Exceptions from Child Threads in Python Multithreading?

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:

  1. The child thread (ExcThread) raises an exception.
  2. Within the child thread's "run" method, the exception information is placed into a queue using sys.exc_info().
  3. In the parent thread (main), a loop continuously checks the queue for any exceptions.
  4. If an exception is caught in the loop, it's printed out for examination.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn