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

Cách catch exception khi dùng Python 'with' statement?

Code có thể viết lại để catch exception như sau:

try:
    with open("myFile.txt") as f:
        print(f.readlines())
except:
    print('No such file or directory')

Chúng ta nhận được kết quả sau:

C:/Users/TutorialsPoint1/~.py No such file or directory