带有消息的C++异常

C++ Exceptions with message

本文关键字:C++ 异常 消息      更新时间:2023-10-16

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

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()] = '';
    this->message = characters;
}

我使用它如下:

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

恐怕构造函数中创建的数组永远不会被删除。但我不知道如何删除它——我应该添加析构函数还是使用完全不同的方法?

更新

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

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

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

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

您可以利用std:string

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

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

然后C++作用域将负责为您清理

在构造函数中,我有

Printer::Printer(boost::asio::io_service& io, unsigned int interval) {
    if (interval < 1) {
        throw std::runtime_error("Interval can't be less than one second");
    }
}

创建对象时

try {
    Printer p{io, 0};
} catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
}

程序将退出并抛出消息。