Generic Exception Handling in Python the “Right Way”

前端 未结 6 1180
夕颜
夕颜 2020-12-23 00:07

Sometimes I find myself in the situation where I want to execute several sequential commands like such:

try:
    foo(a, b)
except Exception, e:
    baz(e)
tr         


        
6条回答
  •  误落风尘
    2020-12-23 00:39

    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)
    

提交回复
热议问题