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;
}

4 thoughts on “St9exception with libstdc++

  1. 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.

  2. I never thought I would find the solution just by typing “St9exception” in google… !
    thank you!

Comments are closed.