Exceptions in threads?

Peter Hansen peter at engcorp.com
Mon Sep 22 03:23:56 CEST 2003

Roy Smith wrote:
> 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.


More information about the Python-list mailing list