views:

85

answers:

1

What is the "correct" way of detecting and handling an exception in another thread in Python, when the code in that other thread is not under your control?

For instance, say you set a function that requires 2 parameters as the target of the threading.Thread object, but at runtime attempt to pass it 3. The Thread module will throw an exception on another thread before you can even attempt to catch it.

Sample code:

def foo(p1,p2):
    p1.do_something()
    p2.do_something()

thread = threading.Thread(target=foo,args=(a,b,c))
thread.start()

Throws an exception on a different thread. How would you detect and handle that?

+3  A: 

I think you can only decorate your target function or subclass threading.Thread to take care of exceptions.

def safer( func ):
    def safer(*args,**kwargs):
        try:
            return func(*args,**kwargs)
        except Exception,e:
            print "Couldn't call", func
            # do_stuff( e )
    return safer


thread = threading.Thread(target=safer(foo),args=(1,2,3))
THC4k
Wow, can't believe I didn't think of this on my own. Thanks!
Bryan Ross