Exceptions in threads?

R

Roy Smith

What is supposed to happen when an exception is raised and not caught in
a thread? The Reference Manual (section 4.2) states "When an exception
is not handled at all, the interpreter terminates execution of the
program, or returns to its interactive main loop", but it looks like
what really happens is the thread is terminated, not the whole program.
If I run the following:

-------
#!/usr/bin/env python

import time
import thread

def bogus ():
raise Exception

thread.start_new_thread (bogus, ())
while 1:
time.sleep (1)
print "still alive"
 
P

Peter Hansen

Roy said:
What is supposed to happen when an exception is raised and not caught in
a thread? The Reference Manual (section 4.2) states "When an exception
is not handled at all, the interpreter terminates execution of the
program, or returns to its interactive main loop", but it looks like
what really happens is the thread is terminated, not the whole program.

The behaviour you observed is generally what seems to happen, though
I'm not sure it's even remotely guaranteed what the behaviour will
be across platforms.

If you want your threads' termination to kill the whole program, I
think you would need to do two things. One is wrap each thread with
a generic exception handler which catches all exceptions that aren't
otherwise caught and sends a signal to the main thread, which would
be set up to wait for such a signal and terminate when it got one.
The second would be to make all threads daemon threads, so that
when the main thread tries to terminate it doesn't wait for the
other threads to finish as it does by default.

None of this will, of course, help you if you have a thread blocked
in, say, a socket connection attempt or something like that.

-Peter
 

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

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top