Generic Exception Handling in Python the “Right Way”

前端 未结 6 1170
夕颜
夕颜 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:31

    If they're simple one-line commands, you can wrap them in lambdas:

    for cmd in [
        (lambda: foo (a, b)),
        (lambda: bar (c, d)),
    ]:
        try:
            cmd ()
        except StandardError, e:
            baz (e)
    

    You could wrap that whole thing up in a function, so it looked like this:

    ignore_errors (baz, [
        (lambda: foo (a, b)),
        (lambda: bar (c, d)),
    ])
    

提交回复
热议问题