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

How to Catch Exceptions from Child Threads in Python Multithreading?

Patricia Arquette
Release: 2024-11-22 10:49:11
Original
818 people have browsed it

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()
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template