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

时间:2017-09-19 12:46:03

标签: 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...

也许这个任务有更好的解决方案?

2 个答案:

答案 0 :(得分:0)

您需要添加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 ...

答案 1 :(得分:0)

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

import test1
def service_func():
   print('Service func')
if__name__ == '__main__':
  service_func()
  test1.some_func()

然后在异常块中调用它:

def exception_function():
    #do whatever you want

这阻止了做最后和另一个条件测试。