【问题标题】:Is it OK to throw exceptions defined in the C++ standard library?可以抛出 C++ 标准库中定义的异常吗?
【发布时间】:2015-07-14 00:21:28
【问题描述】:

我想知道是否可以抛出 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");
}

当然,我们可以这样做:

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

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

【问题讨论】:

  • 有一个完整的标题 &lt;stdexcept&gt;,其中包含现成的异常类供您使用,因此您不要自行发明轮子。

标签: c++ exception exception-handling


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢!我只是不确定&lt;stdexcept&gt; 中的类是否打算供非标准库代码使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-09
  • 1970-01-01
  • 1970-01-01
  • 2013-10-13
  • 2011-03-11
  • 2015-02-13
  • 1970-01-01
相关资源
最近更新 更多