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)
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)
归档时间: |
|
查看次数: |
34256 次 |
最近记录: |