C++核心准则E.17:不要试图在所有函数中捕捉所有异常

时间:2022-07-22
本文章向大家介绍C++核心准则E.17:不要试图在所有函数中捕捉所有异常,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

E.17:不要试图在所有函数中捕捉所有异常

Reason(原因)

Catching an exception in a function that cannot take a meaningful recovery action leads to complexity and waste. Let an exception propagate until it reaches a function that can handle it. Let cleanup actions on the unwinding path be handled by RAII.

在一个无法提供有意义的恢复操作的函数中捕捉错误会导致代码复杂化和冗余。让异常向外传播直到到达一个可以处理它的函数。让RAII处理解旋路径上的清理动作。

Example, don't(反面示例)

void f()   // bad
{
    try {
        // ...
    }
    catch (...) {
        // no action
        throw;   // propagate exception
    }
}
Enforcement(实施建议)
  • Flag nested try-blocks.
  • 标记嵌套的try代码块。
  • Flag source code files with a too high ratio of try-blocks to functions. (??? Problem: define "too high")
  • 识别try代码块数相对函数个数比例过高的源文件。