Python中的通用异常处理“正确的方式” [英] Generic Exception Handling in Python the "Right Way"

查看:169
本文介绍了Python中的通用异常处理“正确的方式”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候,我发现自己处于这样的情况,我想执行几个顺序命令:

  try:
foo(a,b)
除了异常,e:
baz(e)
try:
bar(c,d)
除了异常,e:
baz(e)
...

需要忽略。



这感觉很多,而且过多的语法会导致在阅读代码时难以理解。


$ b $在C中,我将很容易用宏解决这种类型的问题,但不幸的是,这不能在直接python中完成。



问题:如何我最好减少代码占用,并提高代码的可读性。

解决方案

您可以使用 with 语句如果你有python 2.5



  from __future__ import with_statement 
import contextlib

@ contextlib.contextmanager
def handler():
try :
yield
除了异常,e:
baz(e)

你的例子现在变成:

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


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)
try:
    bar(c, d)
except Exception, e:
    baz(e)
...

This same pattern occurs when exceptions simply need to be ignored.

This feels redundant and the excessive syntax causes it to be surprisingly difficult to follow when reading code.

In C, I would have solved this type of problem easily with a macro, but unfortunately, this cannot be done in straight python.

Question: How can I best reduce the code footprint and increase code readability when coming across this pattern?

解决方案

You could use the with statement if you have python 2.5

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)

这篇关于Python中的通用异常处理“正确的方式”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆