howdoI: Exception in thread - terminating the program?

David Bolen db3l at
Tue Jul 17 20:25:14 CEST 2001

Ville Vainio <vvainio at> writes:

> Is there some "standard" or canonical way to make programs die when an
> unhandled exception occurs in a thread (other than main)? Off the top
> of my head, I can think of having a threading.Event blocking at the
> main, all threads set to Daemons, and having the run() in catch-all
> try-except block (and save/print traceback, trigger the blocking event
> in main inside except).

That's certainly one reasonable approach.  In general, if you're doing
a multi-threaded application, except in some very self-contained cases
you're likely to to need a means to communicate amongst the threads
for some synchronization purposes, either to retrieve results of
operations or affect the operations at hand.  So typically before
you're done you're going to find yourself needing some signaling
mechanism anyway, and often that can then be used to cover cases such
as this.

If your main thread isn't going to be doing anything but spinning up
the other threads, then having it wait on such an event is fine -
although you may want to consider having it read from a queue, and
thus be able to not only receive information from failing threads (the
failing thread could even send over the traceback object through the
queue so the main thread could handle printing/logging duties for all
operational threads), but also completion or other communication from
properly working threads.

If the main thread is doing other activities, you could either
periodically check at the event or queue, or even just poll the
other threads with isAlive() to ensure they are still running.

If you're going to encapsulate this in a GUI at some point, then the
threads can likely generate events to the main GUI thread which can
also serve to communicate such information.

There's also the consideration of how you want to shut down if a
thread terminates (or if under some other condition you want to exit).
Having the worker threads all daemons ensures you can just exit, but
if you need to permit them to perform cleanup, you may actually want a
path from the main thread to the worker threads (e.g., have them check
a terminate flag or event periodically in their execution path) as well.

Which of these various methods is "best" is heavily dependent on your
application and its design goals and constraints.

-- David
 \               David Bolen            \   E-mail: db3l at  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \

More information about the Python-list mailing list