Cơ BảnPython iconPython

Exception handling — `try/except/else/finally` hoạt động thế nào?

  1. try — khối code có thể raise exception
  2. except — xử lý exception
  3. else — chạy nếu KHÔNG có exception trong try
  4. finally — LUÔN chạy, dù có exception hay không — dùng để cleanup
python
try:
    result = 10 / divisor
except ZeroDivisionError as e:
    print(f"Error: {e}")
except (TypeError, ValueError):
    print("Type or value error")
else:
    print(f"Success: {result}")  # Chỉ khi không có exception
finally:
    print("Cleanup")  # Luôn chạy

Xem toàn bộ Python cùng filter theo level & chủ đề con.

Mở danh sách Python