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

ra1*_*ter 5 c++ exception-handling exception

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

#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");
}
Run Code Online (Sandbox Code Playgroud)

当然,我们可以这样做:

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;
}
Run Code Online (Sandbox Code Playgroud)

我读到这里,该std::stoi系列函数抛出一个std::invalid_exception异常,当他们收到了无效的参数; 这就是上述想法的来源.

Jer*_*fin 5

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

另请注意,您可以从标准类派生,因此如果您可以添加显着更高的精度或标准类中不存在的新行为,您可能仍希望将其用作基类。

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