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

มี Standard Way ใช้ Exception Chains ใน Python 3 หรือไม่

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

ปัญหา Python 2: Exception A หายไปถ้า Exception B เกิดระหว่าง handling

Python 3 Solution:

try:
    s = {'a':1, 'b':2}['c']
except KeyError as e:
    raise ValueError('failed') from e

ผลลัพธ์ Python 3

Traceback (most recent call last):
  File "source_file.py", line 2, in 
    s = {'a':1, 'b':2}['c']
KeyError: 'c'

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

Traceback (most recent call last):
  File "source_file.py", line 4, in 
    raise ValueError('failed') from e
ValueError: failed

Attribute __cause__ เก็บ direct cause, __context__ เก็บ implicit context