Search code examples
c++exception

Creating custom exceptions in C++


I am learning C++ and I am experiencing when I try and create my own exception and throw them on Linux.

I've created a small test project to test my implementation and below is my exception class header file.

class TestClass : public std::runtime_error
{
public:
    TestClass(char const* const message) throw();
    virtual char const* what() const throw();
};

The source file for the exception class is

using namespace std;

TestClass::TestClass(char const* const message) throw()
    : std::runtime_error(message)
{

}

char const * TestClass::what() const throw()
{
    return exception::what();
}

In my main app, I am calling a function which throws my exception and catches it in a try/catch as follows:

void runAFunctionAndthrow();

/*
 * 
 */
int main(int argc, char** argv) {
    try
    {
        cout << "About to call function" << endl;
        runAFunctionAndthrow();
    }
    catch (TestClass ex)
    {
        cout << "Exception Caught: " << ex.what() << endl;
    }

    return 0;
}

void runAFunctionAndthrow()
{
    cout << "going to run now. oh dear I need to throw an exception" << endl;

    stringstream logstream;
    logstream << "This is my exception error. :(";
    throw TestClass(logstream.str().c_str());
}

When I run I'm expecting to get the following output:

About to call function

Going to run now. oh dear I need to throw an exception

Exception Caught: This is my exception error. :(

Instead what I am getting is

About to call function

going to run now. oh dear I need to throw an exception

Exception Caught: std::exception

Notice the last line it says std::exception instead of my actual exception message "This is my exception error".

Why is this, it works OK on Windows but on Linux it does this.

From what I've seen on various posts what I've done is correct so what am I missing.


Solution

  • Your what() returns:

     return exception::what();
    

    The return value from std::exception::what() is specified as follows:

    Pointer to a null-terminated string with explanatory information.

    That's it. Nothing more, nothing else. The text you're showing certainly qualifies as an "explanatory information". And this is the only requirement for the return value of what() (except for one other one which is not germane here).

    In other words, C++ does not guarantee the exact contents of what you get with what(). what() you see is what() you get, as the saying goes.

    If you want your exception to describe itself, in some way, it's up to you to implement that, as part of your what().