C++核心指导原则: 错误处理

C++ Core Guidelines 整理目录

  1. 哲学部分
  2. 接口(Interface)部分
  3. 函数部分
  4. 类和类层次结构部分
  5. 枚举部分
  6. 资源管理部分
  7. 表达式和语句部分
  8. 性能部分
  9. 并发和并行
  10. 错误处理
  11. 常量和不可变性
  12. 泛型编程
  13. 源文件
  14. 命名和布局建议
  15. 标准库
  16. 其他规则

E: Error handling

E.1: Develop an error-handling strategy early in a design

E.2: Throw an exception to signal that a function can’t perform its assigned task

E.3: Use exceptions for error handling only

E.4: Design your error-handling strategy around invariants

E.5: Let a constructor establish an invariant, and throw if it cannot

E.6: Use RAII to prevent leaks

E.7: State your preconditions

E.8: State your postconditions

E.12: Use noexcept when exiting a function because of a throw is impossible or unacceptable

E.13: Never throw while being the direct owner of an object

E.14: Use purpose-designed user-defined types as exceptions (not built-in types)

E.15: Throw by value, catch exceptions from a hierarchy by reference

E.16: Destructors, deallocation, swap, and exception type copy/move construction must never fail

E.17: Don’t try to catch every exception in every function

E.18: Minimize the use of explicit try/catch

E.19: Use a final_action object to express cleanup if no suitable resource handle is available

E.25: If you can’t throw exceptions, simulate RAII for resource management

E.26: If you can’t throw exceptions, consider failing fast

E.27: If you can’t throw exceptions, use error codes systematically

E.28: Avoid error handling based on global state (e.g. errno)

E.30: Don’t use exception specifications

E.31: Properly order your catch-clauses