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

วิธีใช้ Except Clause กับ Multiple Exceptions ใน Python

ระบุ multiple exceptions ใน tuple เดียว ใช้ as สำหรับ variable

Syntax

except (Exception1, Exception2, ...) as e:

ตัวอย่าง

import sys

try:
    d = 8
    d = d + '5'  # TypeError
except (TypeError, SyntaxError) as e:
    print(sys.exc_info())

ผลลัพธ์

(, TypeError("unsupported operand type(s) for +: 'int' and 'str'",), )

Python 2.6+ รองรับ as, Python 3 ต้องใช้ as เท่านั้น