Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách dùng 'except' clause với multiple exceptions trong Python?

Có thể định nghĩa multiple exceptions với cùng except clause. Nghĩa là nếu Python interpreter tìm matching exception, nó sẽ execute code viết dưới except clause.

Về mặt chung, syntax cho multiple exceptions như sau:

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

Khi chúng ta định nghĩa except clause theo cách này, chúng ta expect cùng code throw different exceptions. Cũng, chúng ta muốn take action trong mỗi case.

Ví dụ code:

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

Chúng ta nhận output như sau:

(<type 'exceptions.TypeError'>, TypeError("unsupported operand type(s) for +: 'int' and 'str'",), <traceback object at 0x0000000002954748>)