首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则E.18:最小限度显式使用try/catch

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

作者头像
面向对象思考
发布2020-08-10 09:55:12
3300
发布2020-08-10 09:55:12
举报

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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-08-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • E.18: Minimize the use of explicit try/catch
  • Reason(原因)
    • Alternatives(其他选项)
      • Enforcement(实施建议)
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档