c++ - 如何修改 C++ runtime_error 的 what 字符串?

标签 c++ exception std runtime-error

我有一个继承自 std::runtime_error 的类,如下所示:

#include <string>
#include <stdexcept>

class SomeEx : public std::runtime_error
{
public:
    SomeEx(const std::string& msg) : runtime_error(msg) { }
};

所述 msg 将始终类似于“无效类型 ID 43”。有什么方法可以用另一个构造函数(或另一种方法)构建那个“what string”,以便我只提供整数类型 ID?像这样的东西:

SomeEx(unsigned int id) {
    // set what string to ("invalid type ID " + id)
}

最佳答案

static std::string get_message(unsigned int id) {
    std::stringstream ss;
    ss << "invalid type ID " << id;
    return ss.str();
}
SomeEx(unsigned int id) 
    : runtime_error(get_message(id)) 
{}

无关:我们有字符串 .what() 的原因是为了让人们停止使用错误数字。

关于c++ - 如何修改 C++ runtime_error 的 what 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9267674/

相关文章:

调试器未捕获到 C# 崩溃

java - 使用 JAX-WS 的 EXCEPTION_STACK_OVERFLOW

c++ - 从函数指针的 std::array 调用函数

c++ - 返回的迭代器有错误的值

c# - 取消任务时的 OperationCanceledException VS TaskCanceledException

c++ - 如何通过id获取线程对象?

C++ : Initializing base class constant static variable with different value in derived class?

c++ - iostream 对象 cin、cout、cerr 和 clog 是如何实现的?

c++:引用父级的成员

c++ - 关于ostream运算符的问题<<