avoiding nested try/excepts

Peter Otten __peter__ at web.de
Fri Nov 19 07:55:34 EST 2004


Steven Bethard wrote:

> (1) Should I really worry about localizing try-except blocks? and, if so

Not when the error-handling doesn't take advantage of the greater locality.

> (2) Is there a cleaner way to do this kind of thing?

I've always thought that catching an exception was the clean way that
replaces dealing with functions returning error codes.

> Note that I can't edit the g or k functions, so I can't move the
> try-except blocks inside.

If you cannot modify, you can still wrap them:

 >>> def catch(*exceptions):
...     def make_catcher(f):
...             def catcher(*args):
...                     try:
...                             return f(*args)
...                     except exceptions:
...                             print "caught it"
...             return catcher
...     return make_catcher
...
>>> @catch(ZeroDivisionError)
... def f(a, b): return a / b
...
>>> f(1, 2)
0
>>> f(1, 0)
caught it
>>>

You may guess at what line in the above it dawned on me that you'd be better
off with individual wrappers than a generalized decorator...

Peter





More information about the Python-list mailing list