我可以从python的finally块中获取异常吗?

Gou*_*ham 33 python error-handling

我的脚本中有一个try/ finally子句.是否有可能从finally子句中获取确切的错误消息?

Ale*_*lli 69

不,finally时间全sys.exc_info是无,是否有异常.使用:

try:
  whatever
except:
  here sys.exc_info is valid
  to re-raise the exception, use a bare `raise`
else:
  here you know there was no exception
finally:
  and here you can do exception-independent finalization
Run Code Online (Sandbox Code Playgroud)

  • @Jonathan只有你在其中一个处理中处理异常时才全部为None. (4认同)
  • 从 Python 3.? 开始,您可以从 `finally:` 块中访问 `sys.exc_info`。 (3认同)

Ian*_*and 12

finally无论是否抛出异常,都将执行该块,因此Josh指出,您很可能不希望在那里处理它.

如果你确实需要引发异常的值,那么你应该在一个except块中捕获异常,并适当地处理它或重新引发它,然后在finally块中使用该值 - 期望如果在执行期间没有引发异常,它可能永远不会被设置.

import sys

exception_name = exception_value = None

try:
    # do stuff
except Exception, e:
    exception_name, exception_value = sys.exc_info()[:2]
    raise   # or don't -- it's up to you
finally:
    # do something with exception_name and exception_value
    # but remember that they might still be none
Run Code Online (Sandbox Code Playgroud)