有时我需要在 for
循环中使用以下模式。有时在同一个循环中不止一次:
try:
# attempt to do something that may diversely fail
except Exception as e:
logging.error(e)
continue
现在我看不到将其包装在函数中的好方法,因为它不能 return continue
:
def attempt(x):
try:
raise random.choice((ValueError, IndexError, TypeError))
except Exception as e:
logging.error(e)
# continue # syntax error: continue not properly in loop
# return continue # invalid syntax
return None # this sort of works
如果我 return None
我可以:
a = attempt('to do something that may diversely fail')
if not a:
continue
但我认为这不公平。我想从 attempt
函数中将 for 循环告诉 continue
(或伪造它)。
原文由 fmalina 发布,翻译遵循 CC BY-SA 4.0 许可协议
Python 已经有一个非常好的构造来执行此操作并且它不使用
continue
:不过,我不会嵌套更多,否则您的代码很快就会变得非常难看。
在您的情况下,我可能会做更多类似的事情,因为对单个函数进行单元测试要容易得多,而且 平面比嵌套更好:
请记住始终 捕获 特定 的异常。如果您不希望抛出 特定 异常,则继续处理循环可能不安全。
编辑以下评论:
如果你真的不想处理异常,我仍然认为这是一个坏主意,那么捕获所有异常(
except:
)而不是handle(e)
,只是pass
。此时wrap_process()
将结束,跳过真正工作完成的else:
块,你将进入你的下一个迭代for
-d5-8环形。请记住, 错误不应该悄无声息地过去。