Có nhiều tình huống muốn chương trình thực hiện tác vụ cụ thể, bất kể chạy thành công hay ném lỗi. Thường dùng try và except để bắt lỗi.
Câu lệnh try cung cấp mệnh đề tùy chọn rất hữu ích để định nghĩa 'clean-up actions' (hành động dọn dẹp) bắt buộc thực thi trong mọi trường hợp.
>>> try:
... raise SyntaxError
... finally:
... print("Learning Python!")
Learning Python!
Traceback (most recent call last):
File "", line 2, in
raise SyntaxError
File "", line None
SyntaxError:
Mệnh đề finally luôn thực thi, tuy nhiên mệnh đề else chỉ chạy nếu không có ngoại lệ được ném ra.
Ví dụ 1: Ghi file thành công (không ngoại lệ)
file = open('finally.txt', 'w')
try:
file.write("Testing1 2 3.")
print("Writing to file.")
except IOError:
print("Could not write to file.")
else:
print("Write successful.")
finally:
file.close()
print("File closed.")
Writing to file.
Write successful.
File closed.
Ví dụ 2: Gây ngoại lệ bằng cách làm file read-only
file = open('finally.txt', 'r')
try:
file.write("Testing1 2 3.")
print("Writing to file.")
except IOError:
print("Could not write to file.")
else:
print("Write successful.")
finally:
file.close()
print("File closed.")
Could not write to file.
File closed.
Trường hợp có lỗi nhưng không có except clause xử lý
Clean-up action (finally) sẽ thực thi trước, sau đó lỗi được ném bởi compiler.
file = open('finally.txt', 'r')
try:
file.write(4)
print("Writing to file.")
except IOError:
print("Could not write to file.")
else:
print("Write successful.")
finally:
file.close()
print("File closed.")
Kết quả
File closed.
Traceback (most recent call last):
File "C:/Python/Python361/finally_try_except1.py", line 4, in
file.write(4)
TypeError: write() argument must be str, not int
Tóm lại: mệnh đề finally luôn thực thi, bất kể có ngoại lệ xảy ra hay không.