gpt4 book ai didi

c++ - 如何使用参数抛出错误消息?

转载 作者:行者123 更新时间:2023-12-03 08:46:19 24 4
gpt4 key购买 nike

我真的很难抛出包含函数参数的错误消息。我知道我可以做到:

throw std::out_of_range("Empty tree");

我正在努力解决的是我应该抛出的另一个错误,即:
"Cannot find ceil for key <key>" 

如您所见,我应该包含无法找到 ceil 的 key 。我在抛出异常的函数中有键作为变量,但我不知道如何将它包含在最终将由 e.what() 打印的内容中。

编辑:这是作为类成员的模板函数,因此 key 现在只需键入 T 。因此,为什么我认为将其格式化为 c 字符串不起作用。

最佳答案

标准异常只接受一个字符串作为参数:

例如超出范围 ,见 apache.org docs

namespace std {
class out_of_range : public logic_error {
public:
explicit out_of_range(const string& what_arg);
};
}

您可以使用任何方法预先构建字符串,然后将其作为参数传递给异常。

示例 :
#include <string>
#include <sstream>
#include <stdexcept>

std::ostringstream oss;
oss << "Cannot find ceil for key " << key;
std::string errorString = oss.str();

throw std::out_of_range(errorString);

有关创建字符串的其他方法,请参阅 C++ create string of text and variables

关于c++ - 如何使用参数抛出错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53072205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com