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

วิธี Catch Multiple Exceptions ในบรรทัดเดียว (Except Block) Python

ใช้ tuple ใน except clause ใช้ as สำหรับ variable

Syntax

try:
    raise_certain_errors()
except (CertainError1, CertainError2, ...) as e:
    handle_error()

Python 2.6/2.7: comma ยังทำงานแต่ deprecated

Python 3: ต้องใช้ as เท่านั้น

Parentheses จำเป็น เพราะ comma ใช้ assign error object

ตัวอย่าง

try:
    # do something
except (someException, someotherException) as err:
    # handle_exception()