Here’s something I encountered today when writing some C++:
try
{
throw std::runtime_error("some message");
}
catch (std::exception e)
{
std::cout << "error: " << e.what() << std::endl;
}
When run, this code will write “error: St9exception”, instead of “some message” to stdout. “St9exception” comes from libstdc++, in which the default value returned by std::exception::what() is the mangled symbol name. The mistake was that I was catching the exception by value, not by reference. (Too much C# perhaps?)
Instead it should have of course been:
try
{
throw std::runtime_error("some message");
}
catch (const std::exception & e)
{
std::cout << "error: " << e.what() << std::endl;
}
March 9, 2008



2 Comments
joe on March 17, 2009 at 7:55 pm.
Great, I had the same bug in my code, you helped me to spare a few minutes.
Ron on June 11, 2011 at 9:26 am.
Thanks, worked like a charm :-)
The funny thing is that catching by value did work on Microsoft’s Visual Studio (2010), but not on the Unix’s gcc.