從中提出的鏈異常

在處理異常的過程中,你可能希望引發另一個異常。例如,如果在從檔案讀取時獲得 IOError,則可能需要引發特定於應用程式的錯誤以呈現給庫的使用者。

Python 3.x >= 3.0

你可以連結異常以顯示如何處理異常:

>>> try:
    5 / 0
except ZeroDivisionError as e:
    raise ValueError("Division failed") from e

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ValueError: Division failed