前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则E.26:如果无法抛出异常,尽快进行失败处理​

C++核心准则E.26:如果无法抛出异常,尽快进行失败处理​

作者头像
面向对象思考
发布2020-08-13 11:26:46
3580
发布2020-08-13 11:26:46
举报
文章被收录于专栏:C++核心准则原文翻译

E.26: If you can't throw exceptions, consider failing fast

E.26:如果无法抛出异常,尽快进行失败处理

Reason(原因)

If you can't do a good job at recovering, at least you can get out before too much consequential damage is done.

如果你无法很好的从错误中恢复,至少你可以在更多危害发生之前退出。

See also: Simulating RAII

参见:模仿RAII方式进行资源管理

Note(注意)

If you cannot be systematic about error handling, consider "crashing" as a response to any error that cannot be handled locally. That is, if you cannot recover from an error in the context of the function that detected it, call abort(), quick_exit(), or a similar function that will trigger some sort of system restart.

如果你不能进行系统化的错误处理,可以将”失败“视为任何无法局部处理的错误的反应。也就是说,如果你无法在检出问题的函数上下文中从错误中恢复,可以调用about函数,quick_exit()函数或者类似的可以触发某种系统重启的函数。

In systems where you have lots of processes and/or lots of computers, you need to expect and handle fatal crashes anyway, say from hardware failures. In such cases, "crashing" is simply leaving error handling to the next level of the system.

在包含很多任务或者大量计算机的系统中,反正你已经需要预估和处理(包括硬件错误的)致命失败。在这样的情况下,”失败“仅仅是将错误处理转交给系统的下一层。

Example(示例)

代码语言:javascript
复制
void f(int n)
{
    // ...
    p = static_cast<X*>(malloc(n * sizeof(X)));
    if (!p) abort();     // abort if memory is exhausted
    // ...
}

Most programs cannot handle memory exhaustion gracefully anyway. This is roughly equivalent to

大多数程序都无法满意的处理内存枯竭。这差不多和下面的代码等价:

代码语言:javascript
复制
void f(int n)
{
    // ...
    p = new X[n];    // throw if memory is exhausted (by default, terminate)
    // ...
}

Typically, it is a good idea to log the reason for the "crash" before exiting.

通常,在因为”失败“退出之前记录原因是好想法。

Enforcement(实施建议)

Awkward

不容易

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e26-if-you-cant-throw-exceptions-consider-failing-fast

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

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

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

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

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