如果引发/捕获任何异常,如何有效地退出python程序

时间:2017-04-20 20:48:06

标签: python exception-handling

说我有一块异常声明:

try:
    expression
except err1:
    #process error
    ...
    ...
except err10:
    #process error

如果引发任何异常,我想调用sys.exit(1)。我是否必须在每个子块中手动调用它,或者是否有内置方式来声明类似于:

    ...
except err10:
    #process error
"if any of these exception were raised":
    sys.exit(1)

4 个答案:

答案 0 :(得分:4)

你可以做的一件事是:

flag = False

try:
    expression
    flag = True
except err1:
    #process error
    ...
    ...
except err10:
    #process error
if not flag:
    sys.exit(1) #exit program

如果该标志为False,则表示您没有通过try循环,因此引发了错误。

答案 1 :(得分:3)

在Python中,有一个可选的else块,在没有引发异常的情况下执行。您可以使用它为您的代码设置一个标志,并将代码从try/except块中退出:

is_exception = True

try:
    expression
except err1:
    # ... something
except err10:
    # ... something else
else:
    # This will be executed if there is no exception
    is_exception = False

if is_exception:
    sys.exit(1)

答案 2 :(得分:1)

raised = True
try:
    expression
except err1:
    # process error
    raise

...

except err10:
    # process error
    raise
else:
    # if no error was raised
    raised = False
finally:
    if raised:
        raise SystemExit

答案 3 :(得分:1)

以下是我在评论中谈到的内容:

for u,v,d in g.edges():
    d['weight'] = 1
g.edges(data=True)
edges = g.edges()
weights = [g[u][v]['weight'] for u,v in edges]