是否可以抛出 C++ 标准库中定义的异常?

Is it OK to throw exceptions defined in the C++ standard library?

我想知道是否可以抛出 C++ 标准库中定义的异常,而不是创建我自己的 class。例如,让我们考虑以下将一个字符串作为参数的(愚蠢的)函数:

#include <stdexcept> 
#include <iostream>
#include <string>

bool useless_function(const std::string& str) {
    if (str == "true")
        return true;

    else if (str == "false")
        return false;

    else
        throw std::invalid_argument("Expected argument of either true or false");
}

当然,我们可以这样做:

int main(int argc, const char** argv) {
    try {
        const bool check = useless_function("not true");
    }

    catch (std::invalid_argument& error) {
        std::cerr << error.what() << '\n';
    }

    return 0;
}

我读到 here std::stoi 函数族在收到无效参数时抛出 std::invalid_exception 异常;这就是上述想法的来源。

是的,为您自己的目的使用标准异常 classes 是完全可以的。如果它们很适合您的情况,请继续(但不要犹豫,定义您自己的 class when/if 没有标准 class 适合)。

另请注意,您可以从标准 classes 派生,因此如果您可以添加标准 class 中不存在的显着更高的精度或新行为,您可能仍然需要将其用作基础 class.

更好的问题 (IMO) 是什么时候定义您自己的异常 class 是有意义的(至少不是从标准异常中派生出来的)。这里一个明显的候选者是,如果你想支持类似 what() 的东西,returns 一个像 UTF-16 或 UTF-32 编码的字符串,所以 "stock" "std::exception" 不会提供太多(如果有的话)实用程序,你几乎无法从头开始。