Wrapping exception handling around a function

Hans Nowak hans at zephyrfalcon.org
Thu Feb 12 13:49:45 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

Hm.  What happens if you call this function for the second time?  _first will 
be false, and 'bad' will not be set.

It appears that all you want is to log the exception to a file... create it if 
it doesn't exist, append to it otherwise.  So you might be better off doing 
something like

   except tuple(catchtuple), message:
       bad = file(badfile, 'a+')
       traceback.print_exc(100, bad)
       bad.close()
       raise LocalError

HTH,

-- 
Hans (hans at zephyrfalcon.org)
http://zephyrfalcon.org/






More information about the Python-list mailing list