An important point to consider when writing multithreaded applications is how do we handle any exceptions thrown in child threads? We looked at cross-thread communication in the previous chapter, so a logical method for catching and communicating exceptions between child and parent threads could be to use one or more of the techniques we have already discussed.
In this next code sample, we'll look at exactly how you can communicate any exceptions thrown from a child thread to the parent thread. We'll be utilizing the sys module to extract the information we need about the exception, and then place this within the confines of our thread-safe queue primitive:
import sys
import threading
import time
import queue
def myThread(queue):
while True:
try:
time.sleep(2)
raise Exception("Exception Thrown In Child Thread {}".format(threading.current_thread()))
except:
queue.put(sys.exc_info())
queue = queue.Queue()
myThread = threading.Thread(target=myThread, args=(queue,))
myThread.start()
while True:
try:
exception = queue.get()
except Queue.Empty:
pass
else:
print(exception)
break
When you run this preceding Python program, you'll see that the child thread throws an error two seconds after it starts; this error is put into the thread-safe queue object which our parent thread then reads from. We are then able to handle the exception in any way we wish within our parent thread.
[20:22:31] ~/Projects/Python/Chapter 06 master✘
$ python3.6 07_threadException.py
(<class 'Exception'>, Exception('Exception Thrown In Child Thread <Thread(Thread-1, started 123145552101376)>',), <traceback object at 0x102320548>)