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

Best practices cho exception handling trong Python?

Một số best practices cho exception handling trong Python:

  • Exceptions tốt hơn returning error status codes. Chúng ta phải handle exceptions trong Python vì toàn bộ language core và standard libraries throw exceptions. Elegantly handled exceptions tốt hơn error codes và trace backs.
  • Không nên dùng exceptions cho flow-control.
  • Exceptions xảy ra trong exceptional situations không phải part của normal execution.
  • Xét 'find' trên string trả về -1 nếu pattern không tìm thấy, nhưng indexing beyond end của string raise exception. Không tìm thấy string là normal execution.
  • Tốt hơn handle exceptions ở level mà chúng ta biết cách handle chúng.
  • Best place là piece of code có thể handle exception. Với một số exceptions, như programming errors (IndexError, TypeError, NameError v.v.) exceptions tốt nhất để cho programmer, vì "handle" chúng có thể che giấu real bugs.
  • Luôn hỏi "đây có phải nơi đúng để handle exception này không?" và cẩn thận với catching all exceptions.
  • Chúng ta nên document exceptions thrown bởi code của chúng ta. Suy nghĩ về exceptions code có thể throw giúp viết code tốt hơn, an toàn hơn và encapsulated hơn.