capture exception raised by child thread.

J

Joe Wong

Hi,

I have a class that created a child thread for processing, this thread might raise an exception under some condition. On the main program that create an object of this case, I put a try/except block trying to capture the exception but failed. Am I doing anything wrong here?

here is the stripped version of my code:

class A:
def __init__(self):
self.thread = threading.Thread(None, self.MyThread)
self.thread.setDaemon(1)
self.thread.start()

def MyThread(self):
while 1:
# do something. if error:

if error:
raise exception

in my Main program:

main()
a = A()
while 1:
try:
# do something..
except exception, e:
# I should capture the exception from A, but not..
 
Y

Ype Kingma

Joe said:
Hi,

I have a class that created a child thread for processing, this thread
might raise an exception under some condition. On the main program that
create an object of this case, I put a try/except block trying to capture
the exception but failed. Am I doing anything wrong here?

See the modifications to your code. I hope I got all the
names right, it's been a while, but it should give you an idea
about one way how to do it.
here is the stripped version of my code:

class A:
def __init__(self):
self.thread = threading.Thread(None, self.MyThread)
self.thread.setDaemon(1)

It's a bit unusual for a deamon thread to end in an exception,
but that doesn't matter.

self.caughtException = None
self.endEvent = Event() # from the threading module iirc.
self.thread.start()

def MyThread(self):
try:
try:
while 1:
# do something. if error:

if error:
raise exception
except exc:
self.caughtException = exc
# evt. raise exc again
finally:
self.endEvent.set()
in my Main program:

main()
a = A()
while 1:
# do something..

# test (or wait) for the event from a here.
if a.endEvent.isSet() and a.caughtException:
...

Have fun,
Ype
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,266
Messages
2,571,087
Members
48,773
Latest member
Kaybee

Latest Threads

Top