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

2020-08-05 23:26:19 浏览数 (1)

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(反面示例)

代码语言:javascript复制
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代码块数相对函数个数比例过高的源文件。

0 人点赞