我有一个嵌套的try-except finally块,我在其中连续运行几个函数(假设前面的函数可以工作)。我有一个条件,我在开始时检查(本质上是检查函数是否已经在当天运行),如果这条语句是假的,我想直接跳到最后。
我可以通过强制错误发生来做到这一点(即写入x=1/0,但似乎应该有更好的方法来做到这一点)。
我的代码如下所示:
error = False
conditions = False
try:
# Do stuff here
if not condition:
# Here I want to go directly to finally
except Exception:
error = True
else:
try:
# Do stuff here
except Exception:
error = True
else:
try:
# Do stuff here
except Exception:
error = True
finally:
if error:
# Report that an error occurred
else:
# Report that everything went well发布于 2020-10-19 17:58:54
这个怎么样?
为了在对这个答案的评论中使用MisterMiyagi的出色措辞,它颠倒了逻辑,只有在满足条件时才继续。
error = False
conditions = False
try:
# Do stuff here
except Exception:
error = True
else:
if condition: # The inverted condition moved here.
try:
# Do stuff here
except Exception:
error = True
else:
try:
# Do stuff here
except Exception:
error = True
finally:
if error:
# Report that an error occurred
else:
# Report that everything went wellhttps://stackoverflow.com/questions/64424894
复制相似问题