如果发生任何异常,就执行一些操作

2024-05-01 22:05:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要执行代码,只有当任何异常发生。 我尝试使用以下代码:

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...

也许有更好的解决方案?你知道吗


Tags: 代码trueifasexceptionargscodesome
2条回答

您需要添加except Exception块来捕获以前未列出的常规异常:

...
except OSError as e:
    exception_happened = True
    logger.critical("Error {0}: {1}".format(e.errno, e.strerror))
except subprocess.CalledProcessError as e:
    exception_happened = True
    logger.critical("Subprocess exit with 1")
except Exception as e:
    # any other exception will land here
    ...

finally的用法是pretty different use case。你知道吗

[更新]正如评论中指出的,也许这就是你想要的:

try:
    ...
except Exception as e:
    if isinstance(e, ValueError):
        # do something
    elif ...

正如我在评论中说的,也许你想做:

def exception_function():
    #do whatever you want

然后在异常块中调用它:

try:
    out = zabbix_get(ip='127.0.0.1')
except OSError as e:
    exception_function()
    logger.critical("Error {0}: {1}".format(e.errno, e.strerror))
except subprocess.CalledProcessError as e:
    exception_function()
    logger.critical("Subprocess exit with 1")

防止做最后和另一个条件测试。你知道吗

相关问题 更多 >