繁体   English   中英

带有消息的 C++ 异常

[英]C++ Exceptions with message

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

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

我使用它如下:

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

程序将退出并抛出消息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM