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.
如果你無法很好的從錯誤中恢復,至少你可以在更多危害發(fā)生之前退出。
See also:?Simulating 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.
如果你不能進行系統(tǒng)化的錯誤處理,可以將”失敗“視為任何無法局部處理的錯誤的反應。也就是說,如果你無法在檢出問題的函數(shù)上下文中從錯誤中恢復,可以調(diào)用about函數(shù),quick_exit()函數(shù)或者類似的可以觸發(fā)某種系統(tǒng)重啟的函數(shù)。
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.
在包含很多任務或者大量計算機的系統(tǒng)中,反正你已經(jīng)需要預估和處理(包括硬件錯誤的)致命失敗。在這樣的情況下,”失敗“僅僅是將錯誤處理轉(zhuǎn)交給系統(tǒng)的下一層。
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
大多數(shù)程序都無法滿意的處理內(nèi)存枯竭。這差不多和下面的代碼等價:
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,通過可執(zhí)行的示例對23 個設計模式逐個進行說明。這樣一方面可以使讀者了解真實的軟件開發(fā)工作中每個設計模式的運用場景和想要解決的問題;另一方面通過對這些問題的解決過程進行說明,讓讀者明白在編寫代碼時如何判斷使用設計模式的利弊,并合理運用設計模式。
對設計模式感興趣而且希望隨學隨用的讀者通過本書可以快速跨越從理解到運用的門檻;希望學習Python GUI 編程的讀者可以將本書中的示例作為設計和開發(fā)的參考;使用Python 語言進行圖像分析、數(shù)據(jù)處理工作的讀者可以直接以本書中的示例為基礎,迅速構建自己的系統(tǒng)架構。
覺得本文有幫助?請分享給更多人。
關注微信公眾號【面向?qū)ο笏伎肌枯p松學習每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
