How to except the unexpected?

Scott David Daniels scott.daniels at acm.org
Sun Mar 5 17:23:06 CET 2006


Rene Pijlman wrote:
> Steven D'Aprano:
>> The OP is doing it because catching all exceptions masks bugs. There are
>> certain exceptions which should be allowed through, as they indicate a bug
>> in the OP's code. Normally the tactic is to catch only the exceptions you
>> are interested in, and let everything else through, but the OP needs to
>> catch all exceptions because there are rare exceptions which he can't
>> predict in advance.
> 
> ... This is in a multithreaded ZODB-application....
> When an unexpected exception occurs and remains uncaught, a thread
> terminates, ....

At the base of the thread code, you could put

     import sys, threading, logging

     class MyThread(threading.Thread):
         def run(self):
             try:
                 threading.Thread.run(self)  # or whatever
             except:
                 etype, error, traceback = sys.exc_info()
                 logging.warning('Exception %s: %s seen at %s' %
                      (etype.__name__, error, _someformat_(traceback)))
                 _try_to_rescue_or remove_this_thread_

If the condition is infrequent enough.  If not (if you run a real
risk of multiple threads accessing the log simultaneously), have
a queue of log messages that you feed to a single logging thread.

-- 
-Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list