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

Cách catch IndexError Exception trong Python?

IndexError được raise khi sequence reference out of range.

Code cho trước được viết lại như sau để catch exception và tìm type của nó.

Ví dụ

import sys
try:
    my_list = [3, 7, 9, 4, 6]
    print(my_list[6])
except IndexError as e:
    print(e)
    print(sys.exc_type)

Kết quả

C:/Users/TutorialsPoint1~.py list index out of range
<type 'exceptions.IndexError'>