首先,我不确定我的方法是否合适,所以我愿意接受各种建议.
如果在代码中经常重复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语句吗?