C++ C++;消息异常
我不确定我的自定义异常方法是否正确。我想做的是对自定义消息抛出异常,但似乎是我造成了内存泄漏C++ C++;消息异常,c++,exception,custom-exceptions,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::Load
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()”时会显示一些随机输出您可以利用
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++范围将负责清理你的事情
<抛出std::runtime_错误(“我自己的消息”)在我拥有的构造函数中编码>
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");
}
}
Printer::Printer(boost::asio::io\u服务&io,无符号整数间隔){
如果(间隔<1){
抛出std::runtime_错误(“间隔不能小于1秒”);
}
}
当创建对象时
try {
Printer p{io, 0};
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
试试看{
打印机p{io,0};
}捕获(标准::异常&e){
std::cerr只需使用string
来存储消息。或者使用char*
是有原因的吗?不,没有理由使用char*。我将代码更改为string。谢谢。或者使用析构函数删除分配的字符数组。相关的std::exception已经保证了自定义消息的存储。为什么不重新设置-使用。即使从std::exception派生,您仍然可以使用该功能。最好传递非常量值并移动构造message\uu
谢谢。它是这样工作的,但我不知道为什么…看起来字符串被复制到了异常对象。对吗?它工作是因为string
分配和解除分配buffer本身。它的功能与您的完全相同,但另外它会删除其析构函数中分配的内存。当异常超出范围时,将调用异常的成员的析构函数。string类负责管理自己的缓冲区,因此在调用其析构函数时,它会自行清理,然后当LoadException超出范围时会发生这种情况。实际上,您还需要指定一个覆盖LoadException::~LoadException()throw(){}
,否则会出现更松散的throw说明符错误。