加载中...

14.10 重新抛出最后的异常


问题

You caught an exception in an except block, but now you want to reraise it.

解决方案

Simply use the raise statement all by itself. For example:

  1. >>> def example():
  2. ... try:
  3. ... int('N/A')
  4. ... except ValueError:
  5. ... print("Didn't work")
  6. ... raise
  7. ...
  8. >>> example()
  9. Didn't work
  10. Traceback (most recent call last):
  11. File "<stdin>", line 1, in <module>
  12. File "<stdin>", line 3, in example
  13. ValueError: invalid literal for int() with base 10: 'N/A'
  14. >>>

讨论

This problem typically arises when you need to take some kind of action in response toan exception (e.g., logging, cleanup, etc.), but afterward, you simply want to propagatethe exception along. A very common use might be in catch-all exception handlers:

try:...except Exception as e:

Process exception information in some way...

Propagate the exceptionraise


还没有评论.