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

面向对象思考

共 2165字,需浏览 5分钟

 ·

2020-08-08 20:47

月季

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(示例)

void f(int n)
{
// ...
p = static_cast(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

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

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


新书介绍

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


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

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




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

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

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



浏览 29
点赞
评论
收藏
分享

手机扫一扫分享

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

手机扫一扫分享

举报