Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Best Practices สำหรับ Exception Handling ใน Python

Best practices สำคัญ:

  1. Exceptions ดีกว่า error codes - Python core และ stdlib ใช้ exceptions
  2. อย่าใช้ exceptions สำหรับ flow control - ใช้สำหรับ exceptional situations เท่านั้น
  3. Handle exceptions ที่ level ที่รู้จักจัดการ - ไม่ควร catch ทุกอย่างที่ low level
  4. Programming errors (IndexError, TypeError, NameError) ควรปล่อยให้ programmer จัดการ ไม่ควร catch ไว้ซ่อน bug
  5. ถามตัวเอง: "นี่เป็นที่เหมาะสมที่จะ handle exception นี้ไหม?"
  6. Document exceptions ที่โค้ดของเราโยน - ช่วยเขียน code ที่ safe และ encapsulated