Generic Exception Handling in Python the “Right Way”

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

    The best approach I have found, is to define a function like such:

    def handle_exception(function, reaction, *args, **kwargs):
        try:
            result = function(*args, **kwargs)
        except Exception, e:
            result = reaction(e)
        return result
    

    But that just doesn't feel or look right in practice:

    handle_exception(foo, baz, a, b)
    handle_exception(bar, baz, c, d)
    

提交回复
热议问题