Jonas Libbrecht
Jonas Libbrecht

Reputation: 777

How to catch Exceptions from thread

I've got this piece of code that starts a thread. Then it waits for a few seconds and then it checks if it got a Event. If it does have an event, the thread is 'canceled'. Else a Exception is thrown.

I want to know how to catch this Exception because I've searched for a long time and did not find a clear answer.

import threading
import time

def thread(args1, stop_event):
    print "starting thread"
    stop_event.wait(10)
    if not stop_event.is_set():
        raise Exception("signal!")
    pass

try:
    t_stop = threading.Event()
    t = threading.Thread(target=thread, args=(1, t_stop))
    t.start()

    time.sleep(11)

    #normally this should not be executed
    print "stopping thread!"
    t_stop.set()

except Exception as e:
    print "action took to long, bye!"

First I've tried this concept with a Python signal but when performing more than 1 signal.alarm, it just got stuck for no reason at all (prob. a bug).

EDIT:
I don't want to extend the already existing class, I want to work with the native defined class.

Also I do not want to loop continuously to check if exceptions occured. I want the thread to pass the exception to its parent method. Therefore the time.sleep(11) action in my code

Upvotes: 3

Views: 7616

Answers (1)

K L
K L

Reputation: 306

Created from my comments on your question.
Try something like this.

import sys
import threading
import time
import Queue


def thread(args1, stop_event, queue_obj):
    print "starting thread"
    stop_event.wait(10)
    if not stop_event.is_set():
        try:
            raise Exception("signal!")
        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(11)

    # normally this should not be executed
    print "stopping 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 "action took to long, bye!"

When run, the Exception "signal!" is raised, and is printed by print exc_obj.

Upvotes: 4

Related Questions