带消息的C++异常

Ale*_*hov 7 c++ exception custom-exceptions

我不确定我的自定义异常方法是否正确.我想要做的是抛出自定义消息的异常,但似乎我创建了内存泄漏...

class LoadException: public std::exception {
private:
    const char* message;
public:
    LoadException(const std::string message);
    virtual const char* what() const throw();
};


LoadException::LoadException(const std::string message) {
    char* characters = new char[message.size() + 1];
    std::copy(message.begin(), message.end(), characters);
    characters[message.size()] = '\0';
    this->message = characters;
}
Run Code Online (Sandbox Code Playgroud)

我用它如下:

void array_type_guard(Local<Value> obj, const std::string path) {
    if (!obj->IsArray()) {
        throw LoadException(path + " is not an array");
    }
}

try {
    objects = load_objects();
} catch (std::exception& e) {
    ThrowException(Exception::TypeError(String::New(e.what())));
    return scope.Close(Undefined());
}
Run Code Online (Sandbox Code Playgroud)

我担心在构造函数中创建的数组永远不会被删除.但我不确定如何删除它 - 我应该添加析构函数还是使用完全不同的方法?

更新:

我实际上尝试使用字符串类,如下所示:

class LoadException: public std::exception {
private:
    const char* msg;
public:
    LoadException(const std::string message);
    virtual const char* what() const throw();
};

LoadException::LoadException(const std::string message) {
    msg = message.c_str();
}

const char* LoadException::what() const throw() {
    return msg;
}
Run Code Online (Sandbox Code Playgroud)

但是无法获取错误消息 - 当我打印"what()"时会显示一些随机输出.

Mon*_*ded 24

怎么样
throw std::runtime_error("My very own message");


NG.*_*NG. 14

你可以利用 std:string

class LoadException: public std::exception {
private:
    std::string message_;
public:
    explicit LoadException(const std::string& message);
    virtual const char* what() const throw() {
        return message_.c_str();
    }
};


LoadException::LoadException(const std::string& message) : message_(message) {

}
Run Code Online (Sandbox Code Playgroud)

然后C++范围将负责为您清理事务

  • 传递非const值并移动构造`message_`会更好 (2认同)