When you throw and unhandled std::runtime_error
, the terminal automatically prints the result of what()
making debugging a lot easier. Example:
#include <iostream>
int main()
{
throw std::runtime_error("This is an error message.\n");
}
Console output:
terminate called after throwing an instance of 'std::runtime_error'
what(): This is an error message.
Custom exception classes derived by this class show the same behaviour, exception classes made from scratch don't do that by default.
But the exception class I want to create must not be derived from std::runtime_error
.. And for debugging purposes, what()
should still be printed after the program crashs - but I can't figure out how to do that no matter what! Can someone help me please?
At the moment, it looks like this:
#include <iostream>
struct Custom_Exception
{
std::string Msg;
Custom_Exception(std::string Error_Msg) noexcept
{
Msg=Error_Msg;
}
std::string what() noexcept
{
return Msg;
}
};
int main()
{
throw Custom_Exception("This is an error message.\n");
}
Console output:
terminate called after throwing an instance of 'Custom_Exception'
No what():
in the error message... Putting a std::cout<<Msg;
into the destructor doesn't help either.
Please help me with your suggestions! Thank you.