使用相同消息重新引发新异常会导致垃圾输出.为什么?
Rethrowing new exception with same message causes garbage output. Why?
我想捕获异常以进一步指定错误消息,然后使用该扩展消息抛出一个新异常。但是,这会导致垃圾输出。为什么?
这是一个MWE:
#include <iostream>
#include <string>
#include <exception>
class myError : public std::exception
{
private:
std::string m_error;
public:
explicit myError( const std::string& error ) :
m_error { error }
{}
explicit myError( const char* error ) :
m_error { error }
{}
const char* what() const noexcept override
{
//return m_error.c_str();
return ("My error: " + m_error).c_str();
}
};
int main()
{
try{
try{
throw myError ( "Error message" );
} catch ( const std::exception& e ) {
throw myError( e.what() );
}
} catch ( const std::exception& e ) {
std::cout << e.what() << "n";
}
return 0;
}
我希望输出是"我的错误:我的错误:错误消息",但相反,它是一个简短的随机字符序列,大概直到命中