11/09/2009

When I catch an exception, the exception message is always “Unknown exception” or “std::exception” instead of the correct message

Answer

You are catching std::exception (or another exception base class) by value. Catch by reference instead, to correctly catch instances of derived classes.

This code will print “Unknown exception” (Visual C++) or “std::exception” (GNU g++):

#include <stdexcept>
#include <iostream>

int main()
{
    try
    {
        throw std::runtime_error("error message");
    }
    catch(std::exception e)
    {
        std::cout << e.what() << std::endl;
    }
}

This code will correctly print “error message”:

#include <stdexcept>
#include <iostream>

int main()
{
    try
    {
        throw std::runtime_error("error message");
    }
    catch(std::exception& e)
    {
        std::cout << e.what() << std::endl;
    }
}

No comments:

Post a Comment