8.5. 异常链

raise 语句允许可选的 from 子句,它通过设置所引发异常的 __cause__ 属性来启用异常链。 例如:

  1. raise RuntimeError from OSError

这在你要转换异常时很有用。 例如:

  1. >>> def func():
  2. ... raise IOError
  3. ...
  4. >>> try:
  5. ... func()
  6. ... except IOError as exc:
  7. ... raise RuntimeError('Failed to open database') from exc
  8. ...
  9. Traceback (most recent call last):
  10. File "<stdin>", line 2, in <module>
  11. File "<stdin>", line 2, in func
  12. OSError
  13. The above exception was the direct cause of the following exception:
  14. Traceback (most recent call last):
  15. File "<stdin>", line 4, in <module>
  16. RuntimeError

跟在 from 之后的表达式必须是一个异常或为 None。 当在一个异常处理程序或 finally 子句中又引发了一个异常时异常链将自动生成。 异常链可使用 from None 形式来禁用:

  1. >>> try:
  2. ... open('database.sqlite')
  3. ... except IOError:
  4. ... raise RuntimeError from None
  5. ...
  6. Traceback (most recent call last):
  7. File "<stdin>", line 4, in <module>
  8. RuntimeError