【发布时间】:2017-09-06 14:37:18
【问题描述】:
我有一个异常类如下:
class FileNotFoundException : public std::exception
{
public:
FileNotFoundException(const char* message) : errorMessage(message){ }
const char* what() const throw() override
{
return this->errorMessage;
}
private:
const char* errorMessage;
};
而我throw这个异常是这样的:
std::string message = "Message";
throw ::FileNotFoundException(message.c_str());
但是当我尝试使用以下方法处理它时:
try
{
// the code that throws
}
catch(::FileNotFoundException& ex)
{
std::string message = ex.what();
}
string 为空。
如果有人可以提供帮助,我将不胜感激。
【问题讨论】:
-
未定义的行为。当您
throw时,您的std::string message超出范围并被销毁,您的errorMessage指向已释放的内存。 -
谢谢,你说的都对。愚蠢的是我没有想到这么简单的事情。