现象:
try {
....
} catch ( NcException &e ) {
cout << e.what() << endl;
return -1;
}
以上代码用于当有 NcException 异常时,打印异常内容,结束当前函数。
实际是打印出的信息是乱码而非预期的异常信息。
原因分析:
以下是NcException::what 的源码
const char* NcException::what() const throw()
{
std::ostringstream oss;
oss << lineNumber;
string message(exceptionName+": "+complaint+"\nfile: "+fileName+" line:"+oss.str());
return message.c_str();
}
返回的是局部变量 message 的 c_str()的结果。
当 what() 返回时,message 被析构了,返回的指针也随之失效。
解决方案:
在NcException 中定义私有成员 message, 见代码第8行
class NcException : public std::exception {
public:
NcException(const std::string& exceptionName,const std::string& complaint,const char* fileName,int lineNumber);
virtual ~NcException() throw();
const char* what() const throw();
private:
std::string exceptionName, complaint, fileName;
std::string message;
int lineNumber;
};
然后修改 NcException::What(), 取消局部变量 message, 使用成员变量 message。 只是由于 what() 是 const 函数,所以对 成员变量 message 的修改需要使用 const_cast.
const char* NcException::what() const throw()
{
std::ostringstream oss;
oss << lineNumber;
const_cast< NcException * >( this )->message
= (exceptionName+": "+complaint+"\nfile: "+fileName+" line:"+oss.str());
return message.c_str();
}