ห่อ with statement ไว้ใน try-except
ตัวอย่าง
try:
with open("myFile.txt") as f:
print(f.readlines())
except:
print('No such file or directory')
ผลลัพธ์
No such file or directory
with statement จะ close file อัตโนมัติ แม้มี exception