C++核心准则E.3:异常应该只用于错误处理

时间:2022-07-22
本文章向大家介绍C++核心准则E.3:异常应该只用于错误处理,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

E.3: Use exceptions for error handling only

E.3:异常应该只用于错误处理

Reason(原因)

To keep error handling separated from "ordinary code." C++ implementations tend to be optimized based on the assumption that exceptions are rare.

保证错误处理和“普通的代码”分离。C++的实现试图以异常处理很罕见为前提进行代码优化。

Example, don't(反面示例)

// don't: exception not used for error handling
int find_index(vector<string>& vec, const string& x)
{
    try {
        for (gsl::index i = 0; i < vec.size(); ++i)
            if (vec[i] == x) throw i;  // found x
    }
    catch (int i) {
        return i;
    }
    return -1;   // not found
}

This is more complicated and most likely runs much slower than the obvious alternative. There is nothing exceptional about finding a value in a vector.

相比于显而易见的其他做法,这段代码更复杂,很有可能执行地更慢。在vector中发现一个值没有什么意外性。

Enforcement(实施建议)

Would need to be heuristic. Look for exception values "leaked" out of catch clauses.

可能需要启发式处理。寻找“泄露”到catch代码段之外的例外值。

原文链接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e3-use-exceptions-for-error-handling-only