发布于 2015-08-30 07:53:14 | 95 次阅读 | 评论: 0 | 来源: 网络整理

问题

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:

>>> def example():
...     try:
...             int('N/A')
...     except ValueError:
...             print("Didn't work")
...             raise
...
>>> example()
Didn't work
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in example
ValueError: invalid literal for int() with base 10: 'N/A'
>>>

讨论

This problem typically arises when you need to take some kind of action in response to an exception (e.g., logging, cleanup, etc.), but afterward, you simply want to propagate the 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 exception raise

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务