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

时间:2022-07-23
本文章向大家介绍C++核心准则E.26:如果无法抛出异常,尽快进行失败处理​,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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<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

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

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