小编sut*_*tre的帖子

在Python中经常重复try/except

首先,我不确定我的方法是否合适,所以我愿意接受各种建议.

如果在代码中经常重复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
Run Code Online (Sandbox Code Playgroud)

例如,对于一行操作,您可以定义异常处理包装器,然后传递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))
Run Code Online (Sandbox Code Playgroud)

这种"解决方案"是否会让事情变得不那么明确?我应该完全写出所有的try/except语句吗?

python exception

20
推荐指数
1
解决办法
5051
查看次数

标签 统计

exception ×1

python ×1