14.10 重新拋出最后的異常

2018-02-24 15:27 更新

問題

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

以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號