C++核心准则E.18:最小限度显式使用try/catch

时间:2022-07-22
本文章向大家介绍C++核心准则E.18:最小限度显式使用try/catch,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

E.18:最小限度显式使用try/catch

Reason(原因)

try/catch is verbose and non-trivial uses are error-prone. try/catch can be a sign of unsystematic and/or low-level resource management or error handling.

try/catch结构冗长,非平凡的用法容易出错。try/catch可以看作是非系统化和低层次资源管理或错误处理的信号。

Example, Bad(反面示例)

void f(zstring s)
{
    Gadget* p;
    try {
        p = new Gadget(s);
        // ...
        delete p;
    }
    catch (Gadget_construction_failure) {
        delete p;
        throw;
    }
}

This code is messy. There could be a leak from the naked pointer in the try block. Not all exceptions are handled. deleting an object that failed to construct is almost certainly a mistake. Better:

代码很凌乱。try代码块中的原始指针可能发生内存泄露。不是所有的异常都会被处理。删除一个构建失败的对象机会当然是一个错误。较好的做法:

void f2(zstring s)
{
    Gadget g {s};
}
Alternatives(其他选项)
  • proper resource handles and RAII
  • 正确使用资源句柄和RAII。
  • finally
  • finally处理
Enforcement(实施建议)

??? hard, needs a heuristic

很难,需要启发式提示。

原文链接 https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e18-minimize-the-use-of-explicit-trycatch