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
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()
.
You need a way to specify a custom error message to std::exception which afaik is not allowed. See this for a possible solution.
You need your own implementation of what() method or use std::runtime_error::what()
as written in comments
Say:
class TestClass : public std::runtime_error
{
std::string what_message;
public:
const char* what() override
{
return what_message.c_str();
}
};
Also, better use noexcept
instead of throw()
and only after you read about them - link.
And in your try-catch:
catch (const TestClass& myException)
Instead of catch(TestClass myException)
- otherwise you do an implicit copy which can potentially result in an exception throw. It also breaks the polymorphism: if you want to catch
pure virtual interface
implementation instance, you would need to use a reference.