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

面向对象思考

共 1533字,需浏览 4分钟

 ·

2020-08-08 20:47

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


新书介绍

以下是本人3月份出版的新书,拜托多多关注!


本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。




觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!


浏览 26
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报