worker thread catching exceptions and putting them in queue

Diez B. Roggisch deets at
Mon Mar 5 17:49:59 CET 2007

Paul Sijben wrote:

> All,
> in a worker thread setup that communicates via queues is it possible to
> catch exceptions raised by the worker executed, put them in an object
> and send them over the queue to another thread where the exception is
> raised in that scope?
> considering that an exception is an object I feel it ought to be
> possible, however I do not see how to go about it.
> does anyone have a pointer towards the solution?

Just raise the exception object found in the queue. Only make sure it _is_
an exception, as you can raise everything. So in your queue-putting-code
you might consider discriminating between the two cases, like this:

while True:
      result = 1, work()
      result = 2, sys.exc_info()[1]

while True:
   kind, result = queue.get()
   if kind == 1:
   elif kind == 2:
      raise result


More information about the Python-list mailing list