前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则E.14:使用根据目的设计的用户定制类型异常(非内置类型)

C++核心准则E.14:使用根据目的设计的用户定制类型异常(非内置类型)

作者头像
面向对象思考
发布2020-08-04 17:09:24
3500
发布2020-08-04 17:09:24
举报
文章被收录于专栏:C++核心准则原文翻译

E.14: Use purpose-designed user-defined types as exceptions (not built-in types)

E.14:使用根据目的设计的用户定制类型异常(非内置类型)

Reason(原因)

A user-defined type is unlikely to clash with other people's exceptions.

用户定义类型不大可能和其他人的异常发生冲突。

Example(示例)

代码语言:javascript
复制
void my_code()
{
    // ...
    throw Moonphase_error{};
    // ...
}

void your_code()
{
    try {
        // ...
        my_code();
        // ...
    }
    catch(const Bufferpool_exhausted&) {
        // ...
    }
}
Example, don't(反面示例)
代码语言:javascript
复制
void my_code()     // Don't
{
    // ...
    throw 7;       // 7 means "moon in the 4th quarter"
    // ...
}

void your_code()   // Don't
{
    try {
        // ...
        my_code();
        // ...
    }
    catch(int i) {  // i == 7 means "input buffer too small"
        // ...
    }
}
Note(注意)

The standard-library classes derived from exception should be used only as base classes or for exceptions that require only "generic" handling. Like built-in types, their use could clash with other people's use of them.

继承自exception的标准库类应该只用于基类或只要求“通常”处理的异常。和内置类型相似,你对它们的使用可能和其他人的使用发生冲突。

Example, don't(反面示例)

代码语言:javascript
复制
void my_code()   // Don't
{
    // ...
    throw runtime_error{"moon in the 4th quarter"};
    // ...
}

void your_code()   // Don't
{
    try {
        // ...
        my_code();
        // ...
    }
    catch(const runtime_error&) {   // runtime_error means "input buffer too small"
        // ...
    }
}

See also: Discussion

参见:话题讨论

Enforcement(实施建议)

Catch throw and catch of a built-in type. Maybe warn about throw and catch using a standard-library exception type. Obviously, exceptions derived from the std::exception hierarchy are fine.

捕捉针对内置类型的throw和catch。也许可以针对使用标准库异常类型的throw和catch发出警告。显然,继承自std::exception的异常类没有问题。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e14-use-purpose-designed-user-defined-types-as-exceptions-not-built-in-types

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Example, don't(反面示例)
  • Note(注意)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档