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

Cách catch SyntaxError Exception trong Python?

SyntaxError xảy ra bất cứ khi parser tìm source code nó không hiểu. Điều này có thể xảy ra khi import module, invoke exec, hoặc gọi eval(). Attributes của exception có thể dùng để tìm chính xác phần nào của input text gây ra exception.

Chúng ta viết lại code để handle exception và tìm type của nó:

Ví dụ

try:
    print(eval('six times seven'))
except SyntaxError as err:
    print('Syntax error %s (%s-%s): %s' % (err.filename, err.lineno, err.offset, err.text))
    print(err)

Kết quả

C:/Users/TutorialsPoint1/~.py
Syntax error  (1-9): six times seven
invalid syntax (, line 1)