Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธี Rethrow Python Exception ด้วย Type ใหม่

Python 3 รองรับ Exception Chaining ด้วย raise ... from

ตัวอย่าง

try:
    1/0
except ZeroDivisionError as e:
    raise ValueError("Sweet n Sour grapes") from e

ผลลัพธ์ Python 3

Traceback (most recent call last):
  File "...", line 2, in 
    1/0
ZeroDivisionError: division by zero

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

Traceback (most recent call last):
  File "...", line 4, in 
    raise ValueError("Sweet n Sour grapes") from e
ValueError: Sweet n Sour grapes

Attribute __cause__ เก็บ original exception