Wrapping exception handling around a function

Peter Otten __peter__ at web.de
Thu Feb 12 11:56:03 EST 2004


Edward C. Jones wrote:

> Is there a better way to write the following?
> 
> --------
> 
> import sys, traceback
> 
> class LocalError(StandardError):
>      pass
> 
> _first = True
> 
> # "fcn(*args)" is executed. If one of the exceptions listed in
> # "catchtuple" is thrown in "fcn", the exception is caught here.
> # The traceback and message are written to "badfile". Then
> # "LocalError" is raised. "wrapper" is useful when testing a
> # collection of functions.
> def wrapper(badfile, fcn, args, catchtuple):
>      global _first
>      try:
>          fcn(*args)
>      except tuple(catchtuple), message:
>          if _first:
>              bad = file(badfile, 'w')
>              _first = False
>          traceback.print_exc(100, bad)
>          raise LocalError

I find, e. g.

wrapper("logfile.txt", file, ["somefile.txt", "w"], (IOError,))

much less readable than

import logging

logger = logging.getLogger("mylogger")

try:
    f = file("somefile.txt", "w")
except IOError:
    logger.exception("some hints")
    raise LocalError("some hints")

and don't mind the few extra keystrokes. As for recording only the first
traceback, I'm not that familiar with the logging module, but I still
recommend it over a selfmade scheme.

Peter






More information about the Python-list mailing list