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

Cách catch LookupError Exception trong Python?

LookupError Exception là Base class cho errors raised khi something không thể tìm thấy. Base class cho exceptions raised khi key hoặc index dùng trên mapping hoặc sequence là invalid: IndexError, KeyError.

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:
    foo = [a, s, d, f, g]
    print(foo[5])
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'>