capture exception raised by child thread.
Ype Kingma
ykingma at accessforall.nl
Fri May 14 07:50:05 EDT 2004
Joe Wong wrote:
> 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
More information about the Python-list
mailing list