【发布时间】: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 异常;这就是上述想法的来源。
【问题讨论】:
-
有一个完整的标题
<stdexcept>,其中包含现成的异常类供您使用,因此您不要自行发明轮子。
标签: c++ exception exception-handling