finally块可以知道是否存在异常

时间:2017-04-09 15:44:25

标签: python exception try-finally

在Python程序中,我有以下结构的代码:

try:
    value = my_function(*args)
finally:
    with some_context_manager:
        do_something()
        if 'value' in locals():
            do_something_else(value)

但是'value' in locals()构造感觉有点脆弱,我想知道是否有更好的方法来做到这一点。

我真正想要的是finally内的代码行为略有不同,具体取决于try块是否引发异常。有没有办法知道是否引发了异常?

3 个答案:

答案 0 :(得分:3)

如果目标是“当提出异常时,做一些不同的事情”,那么:

exception_raised = False
try:
    value = my_function(*args)
except:
    exception_raised = True
    raise
finally:
    with some_context_manager:
        do_something()
        if not exception_raised:
            do_something_else(value)

现在,如果你有多个例外,你实际上做了什么,我建议:

completed_successfully = False
try:
    value = my_function(*args)
else:
    completed_successfully = True
finally:
    with some_context_manager:
        do_something()
        if completed_sucessfully:
            do_something_else(value)

答案 1 :(得分:1)

以下是一些想法:

尝试尝试前设置值:

value = None
try:
    value = my_function(*args)
finally:
    with some_context_manager:
        do_something()
        if value is not None:
            do_something_else(value)

或者,如果要根据异常类型设置值:

try:
    value = my_function(*args)
except:
    value = None
    raise
finally:
    with some_context_manager:
        do_something()
        if value is not None:
            do_something_else(value)

答案 2 :(得分:-1)

将异常分配给except套件中的变量,然后在finally套件中使用它。

foo = False
try:
    raise KeyError('foo not found')
except KeyError as e:
    pprint(e)
    foo = e
finally:
    if foo:
        print(foo)
    else:
        print('NO')