Trong exception handling trong Python, chúng ta dùng try và except statements để catch và handle exceptions. Code trong try clause được execute statement by statement.
Nếu exception xảy ra, phần còn lại của try block bị skip và except clause được execute.
Ví dụ
try:
'apple' + 6
except Exception:
print("Cannot concatenate 'str' and 'int' objects")
Kết quả
Cannot concatenate 'str' and 'int' objects
Chúng ta tránh traceback error message elegantly với simple message như trên bằng cách dùng try except statements cho exception handling.
Ngoài việc dùng except block sau try block, chúng ta cũng có thể dùng finally block. Finally clause là optional. Nó intended để define clean-up actions phải được execute dưới mọi circumstances.
Một finally clause luôn được execute trước khi leaving try statement, whether exception đã xảy ra hay không.
Actions như closing file, GUI hoặc disconnecting từ network, được perform trong finally clause để guarantee execution.
Đây là ví dụ file operations để illustrate finally statement.
Ví dụ
try:
f = open("foo.txt", encoding='utf-8')
# perform file operations
finally:
f.close()
Loại statement này đảm bảo file được close whether exception xảy ra hay không.