我需要执行代码,只有当任何异常发生。 我尝试使用以下代码:
args = [1, 2, 3]
# .... some code ....
exception_happened = True
try:
out = zabbix_get(ip='127.0.0.1')
except OSError as e:
logger.critical("Error {0}: {1}".format(e.errno, e.strerror))
except subprocess.CalledProcessError as e:
logger.critical("Subprocess exit with 1")
else:
exception_happened = False
finally:
if exception_happened:
# .... this code for execute if any exeptions happend...
也许有更好的解决方案?你知道吗
您需要添加
except Exception
块来捕获以前未列出的常规异常:finally
的用法是pretty different use case。你知道吗[更新]正如评论中指出的,也许这就是你想要的:
正如我在评论中说的,也许你想做:
然后在异常块中调用它:
防止做最后和另一个条件测试。你知道吗
相关问题 更多 >
编程相关推荐