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

Cách catch IndentationError Exception trong Python?

IndentationError xảy ra bất cứ khi parser tìm source code không tuân theo indentation rules. Chúng ta có thể catch nó khi import module, vì module sẽ được compile khi import lần đầu. Bạn không thể catch nó trong cùng module chứa try/except block, vì với exception này, Python không thể finish compiling module, và không code nào trong module sẽ chạy.

Chúng ta viết lại code cho trước như sau để handle exception:

Ví dụ

try:
    def f():
        z = ['foo', 'bar']
        for i in z:
            if i == 'foo':
except IndentationError as e:
    print(e)

Kết quả

"C:/Users/TutorialsPoint1/~.py", line 5
if i == 'foo':
^ IndentationError: expected an indented block