带有消息的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()] = ' ';
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;
}
程序将退出并抛出消息。
相关文章:
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 为什么异常不退出程序?
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 是什么导致了Unity 3D中的"错误线程异常"?
- 如何将strftime中的格式错误作为异常捕获
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 尝试使用智能指针时引发异常
- 函数如何通知用户它基于函数原型抛出异常?
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Pytorch torch.cholesky忽略异常