Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Handle Python Exception in Threads



The given code is rewritten to catch the exception

import sys
import threading
import time
import Queue
def thread(args1, stop_event, queue_obj):
print "start thread"
stop_event.wait(12)
if not stop_event.is_set():
try:
raise Exception("boom!")
except Exception:
queue_obj.put(sys.exc_info())
pass
try:
queue_obj = Queue.Queue()
t_stop = threading.Event()
t = threading.Thread(target=thread, args=(1, t_stop, queue_obj))
t.start()
time.sleep(15)
print "stop thread!"
t_stop.set()
try:
exc = queue_obj.get(block=False)
except Queue.Empty:
pass
else:
exc_type, exc_obj, exc_trace = exc
print exc_obj
except Exception as e:
print "It took too long"

OUTPUT

C:/Users/TutorialsPoint1/~.py
start thread
stop thread!
boom!
Updated on: 2019-09-27T11:35:03+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements