14.6 我们在except块中捕获一个异常,现在将它重新抛出
>>> def e():
... try:
... int('N/A')
... except ValueError:
... print("didn`t work")
... raise
...
>>> e()
didn`t work
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in e
ValueError: invalid literal for int() with base 10: 'N/A'
>>>
- 这种情况通常出现在需要对某个异常做响应(比如记录日志,完成清理工作等)
- 但这之后希望将异常再传播出去。一个非常常见的用途就是用在捕获所有异常的处理中
>>> def e():
... try:
... int('N/A')
... except Exception as e:
... # 做一些记录日志等的处理,然后继续抛出异常
... raise
...
>>> e()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in e
ValueError: invalid literal for int() with base 10: 'N/A'
>>>
网友评论