首先,我不确定我的方法是否正确,因此我愿意接受各种建议。经常重复尝试/ Python除外
如果try/except语句经常在代码中重复出现,有没有什么好方法可以缩短它们或避免完全写出它们?
try:
# Do similar thing
os.remove('/my/file')
except OSError, e:
# Same exception handing
pass
try:
# Do similar thing
os.chmod('/other/file', 0700)
except OSError, e:
#Same exception handling
pass
例如,对于一个行操作可以定义一个异常处理的包装,然后通过一个lambda函数:
def may_exist(func):
"Work with file which you are not sure if exists."""
try:
func()
except OSError, e:
# Same exception handling
pass
may_exist(lambda: os.remove('/my/file'))
may_exist(lambda: os.chmod('/other/file', 0700))
这是否“解决方案”只会让事情不太清楚?我应该完全写出所有的try/except语句吗?
[Python的?:尝试 - 除了作为一个表达式]的可能重复(http://stackoverflow.com/questions/7088009/python-try-except-as -an-expression) – agf
我和@ kindall昨天刚刚回答了这个问题。 – agf
@agf:这个问题似乎部分相关,谢谢链接。然而,Ned Batchelder的答案似乎有一个好处,就是不需要为需要捕获异常的代码块创建一个函数。 – sutre