前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则E.3:异常应该只用于错误处理

C++核心准则E.3:异常应该只用于错误处理

作者头像
面向对象思考
发布2020-07-28 15:00:18
2540
发布2020-07-28 15:00:18
举报
文章被收录于专栏:C++核心准则原文翻译

E.3: Use exceptions for error handling only

E.3:异常应该只用于错误处理

Reason(原因)

To keep error handling separated from "ordinary code." C++ implementations tend to be optimized based on the assumption that exceptions are rare.

保证错误处理和“普通的代码”分离。C++的实现试图以异常处理很罕见为前提进行代码优化。

Example, don't(反面示例)

代码语言:javascript
复制
// don't: exception not used for error handling
int find_index(vector<string>& vec, const string& x)
{
    try {
        for (gsl::index i = 0; i < vec.size(); ++i)
            if (vec[i] == x) throw i;  // found x
    }
    catch (int i) {
        return i;
    }
    return -1;   // not found
}

This is more complicated and most likely runs much slower than the obvious alternative. There is nothing exceptional about finding a value in a vector.

相比于显而易见的其他做法,这段代码更复杂,很有可能执行地更慢。在vector中发现一个值没有什么意外性。

Enforcement(实施建议)

Would need to be heuristic. Look for exception values "leaked" out of catch clauses.

可能需要启发式处理。寻找“泄露”到catch代码段之外的例外值。

原文链接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e3-use-exceptions-for-error-handling-only

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • E.3: Use exceptions for error handling only
  • Reason(原因)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档