Skip to content Skip to sidebar Skip to footer

How To Catch An Exception Which Occured In A Thread?

Note: there is one exact answer to my question in the duplicate (also see my answer below for the modified code). Thank you @quamrana for the pointer Context: I have a list of meth

Solution 1:

create a queue to catch exceptions.

errors = queue.Queue()

defthreaded_func():
  try:
    # perform some taskexcept:
    errors.put(  
      # push into queue as required
    )
def main():
  while True and threads_running:
   if errors.__len__():
     error_in_main = errors.pop()
     # handle the error as required.

Using this manner you can almost immideately catch errors in main thread and perform operations as required.

Solution 2:

The exact answer to my problem was given in an answer to another question (I marked mine as duplicate, but it is really that particular answer which is perfect in my context).

The code in my question modified to account for the solution:

import concurrent.futures

classChecks:

    @staticmethoddefisok():
        print("OK")

    @staticmethoddefisko():
        raise Exception("KO")

# db will keep a map of method namles in Check with the actual (executable) method
db = {}

with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
    for check in [k for k indir(Checks) ifnot k.startswith('_')]:
        db[check] = executor.submit(getattr(Checks, check))
    for future in concurrent.futures.as_completed([db[k] for k in db.keys()]):
        if future.exception():
            print(f"{str(future.exception())} was raised (I do not know where, somewhere)")
        else:
            print("success (again, I do not know where, exactly)")

# all the threads are finished at that pointprint("all threads are done")

I do not know how to get the name of the future which raised the exception (I will ask a new question about that)

Post a Comment for "How To Catch An Exception Which Occured In A Thread?"