St9exception with libstdc++

St9exception with libstdc++

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;