14.10 �新抛出被�获的异常¶

问题¶

你在一个 except �中�获了一个异常,现在想�新抛出它。

解决方案¶

简�的使用一个�独的 rasie 语���,例如:

>>> 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'
>>>

讨论¶

这个问题通常是当你需�在�获异常�执行�个�作(比如记录日志�清�等),但是之�想将异常传播下去。 一个很常�的用法是在�获所有异常的处�器中:

try:
   ...
except Exception as e:
   # Process exception information in some way
   ...

   # Propagate the exception
   raise