best idiom for wide try/except net?

Russell E. Owen no at spam.invalid
Thu Jun 19 01:55:33 CEST 2003


I have an application that has to be as robust as possible but also 
loads some user-written modules. it is useful in a few places to catch 
almost any exception and report a detailed traceback, then go on.

So far I've been doing this:

try
  # code that might have bugs
except StandardError:
  sys.stderr.write(...)
  traceback.print_exc(file=sys.stderr)

since catching "Exception" also catches SystemExit, which sounded like a 
bit much. (I'd rather also not catch KeyboardInterrupt, but I can live 
with that).

However, some standard libraries, such as socket, use exceptions which 
are a subclass of Exception, but not a subclass of StandardError. I'm 
wondering if this typical/normal/acceptable for standard libraries or is 
something to be fixed?

The only workaround I've thought of is this, which looks a bit ugly to 
me (it seems a shame to have to explicitly catch stuff I don't want):

try:
  # code that might have bugs
except (SystemExit, KeyboardInterrupt):
  # exceptions I do not want to catch
   throw
except:
   # all other exceptions
  sys.stderr.write(...)
  traceback.print_exc(file=sys.stderr)

Any suggestions?

-- Russell




More information about the Python-list mailing list