Generic Exception Handling in Python the “Right Way”

You could use the with statement if you have python 2.5 or above:

from __future__ import with_statement
import contextlib

@contextlib.contextmanager
def handler():
    try:
        yield
    except Exception, e:
        baz(e)

Your example now becomes:

with handler():
    foo(a, b)
with handler():
    bar(c, d)

Leave a Comment

File not found.